0

I am new to reactjs. I am trying to generically add custom properties to react components. Here is my use case ...

For a react component called HelloWorld, I want the DOM to show the attribute data-js-class="HelloWorld". The reason I want to do this is because when I am inspecting the DOM in dev tools, I can quickly identify the component that rendered that piece of the DOM.

I can do the same thing by going into the React tab of dev tools and jump to the generated DOM element. I can also do the same in the components render() method by adding properties in every single component. But I dont want to do that in every single component. I want it to happen magically at a framework level.

I have tried to backup the React.createElement and write my own custom createElement which eventually calls the original React.createElement() method. It wasnt an elegant solution.

On the base React.Component class, I added a createElement() (to the React.Component.prototype) method. The component's render method calls "this.createElement(...) instead of "React.createElement()". But this is not elegant either because there is JSX too which this solution will not handle.

class HelloWorld extends React.Component {
  render() {
    return React.createElement(
      'h1',
      null, //this.props
      'Hello world'
    )
  }
}

... should render

<h1 data-js-class="HelloWorld">Hello World</h1>

What would be the most elegant way of achieving this?

1 Answer 1

1

What would be the most elegant way of achieving this?

I believe adding the metadata for the sake of reviewing which component generated the DOM.

You can simply go to the React devtool and find out which DOM node was generated as shown below.

demo

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that is one way of checking which component generated the DOM. I did mention that in my initial post. Let's assume this is for academic purpose thought I would like to generate that additional attribute for quick debugging purpose. Any suggestions?
@Praj I can think of two ways. 1. Write a babel plugin to access AST, and add the component name for the prop during build time (when env is dev). 2. Create a HoC, which you need to call when you export each component. (e.g. export default withComponentProp(HelloWorld) ). As it's for academic purpose, I'd go with the babel plugin route 🙂

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.