If you are declaring div like this <div id='message-box'>
you already know the id. I'm not sure why you would need this logic.
As mentioned by @mstoJS you can use refs
. ref
variable (for dom elements) are set only after the component is mounted to the dom.
The trick here is to force a second render to display the value of ref.
You can run the below snippet to see the results.
class Hello extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
this.forceUpdate();
}
render() {
console.log("Rendering");
return <div id = "message-box"
ref = {
this.myRef
} >
Hello {
this.props.name
}
We are in div {
this.myRef.current ? this.myRef.current.id : ""
} <
/div>
}
}
ReactDOM.render( < Hello name = "Pooja" / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Why I used this.myRef.current ? this.myRef.current.id : ""
That's because a ref
to a dom
element is assigned only after a component is mounted to dom (let's say displayed on browser) and render
happens before component is mounted to dom.
You can run the below snippet and watch the order of componentWillMount
, render
and componentDidMount
through the console.log
statements.
You should be able to see that the ref
is initialized after render
method(Its available in componentDidMount
which runs after render
).
class Hello extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log("3. Component is mounted on dom. Value of myRef is ", this.myRef.current);
//this.forceUpdate();
}
componentWillMount(){
console.log("1. Component is about to mount on dom. Value of myRef is ", this.myRef.current);
}
render() {
console.log(
"2. Component is rendering. Value of myRef is ",
this.myRef.current
);
return (
<div id="message-box" ref={this.myRef}>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(<Hello />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
this.myRef.current ? this.myRef.current.id : ""
ensures that I'm not accessing a property of a null object (Which obviously throws error) on first render, but is available for use on second render (which I'm forcing through this.forceUpdate()
in componentDidMount
).