Radex
Radex

Reputation: 8587

adding a dom id on a component

I have a react component as

<Component />

render(){
   return <div>Component </div>
}

and I would like to render it in the dom with an additional id, passing it like

<Component id={'myId'} />

I do not want to change the internal render of <Component /> and I would like to do not wrap it.

Is it possible to achieve this in react?

Upvotes: 0

Views: 825

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

I do not want to change the internal render of and I would like to do not wrap it.

If by "change the internal render of <Component />" you mean changing what you're returning from its render, then you're out of luck. Doing that or wrapping it are your only options; once rendered, the div is your component's top-level element. There's nowhere else to put the id.

So you'd put it on the div:

render() {
    return <div id={this.props.id}>Component </div>;
}

Live Example (using Example rather than Component to avoid confusion):

class Example extends React.Component {
  render() {
    return <div id={this.props.id}>Component </div>;
  }
}

ReactDOM.render(
  <Example id={'myId'} />,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

If you right-click the text "Component" above and examine the DOM, you'll find that the component isn't wrapped or anything like that. (The id="root" element you see is just where I mounted it in the DOM, since React warns against mounting directly on document.body.)

Upvotes: 2

Related Questions