user2465134 user2465134 - 1 year ago 61
React JSX Question

React - Can't use refs in child component when rendering them depending on state

I ran into a weird bug trying to use refs.

Parent component:

class Parent extends Component {
constructor(props) {

this.state = {displayPage: 'one'};
this.changePage = this.changePage.bind(this);

displayPage: str

<div onClick={ () => this.displayPage('one')}>One</div>
<div onClick={ () => this.displayPage('two')}>Two</div>
<div onClick={ () => this.displayPage('three')}>Three</div>

{this.state.displayPage === 'one' ? <One /> : true}
{this.state.displayPage === 'two' ? <Two /> : true}
{this.state.displayPage === 'three' ? <Three /> : true}

Now, just a simple example of a child component:

class Two extends Component {
console.log(this, this.refs)

<div refs="test">This is the Two component</div>

My problem is that the console.log for "this" will show a property of "refs" that has everything I want. When it logs "this.refs" all I get back is "Object {}". This will only happen in components Two and Three, or basically, the components that aren't immediately displayed because of the state. "this.refs" will always work for the component immediately displayed.

Also, if I took them out of the ternary condition then refs will work as intended.

Answer Source

change refs in the div to ref like such:


also, just assigning refs by string is getting deprecated, so I suggest you just pass in a callback to a ref that reassigns it as a static property to the class like this:

ref={(node) => { this.test = node; }}