Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ref in (conditional render)

I want to use ref, however I am not able to use this in the conditional rendering which is initially false.

constructor(props) {
    super(props);
    this.state = { 
      filterActive: false,
    }
    this.firstRef = React.createRef();

}

If I use ref in this :-

{this.state.filterActive ?
    <label ref={this.firstRef}>Time Range</label>
:null}

The ref is null.

like image 322
Anup Mishra Avatar asked Sep 25 '19 09:09

Anup Mishra


People also ask

How do you conditionally add a ref in React?

You can use the props spread operator {... props} to pass a conditional ref by building the props object first. E.g. Show activity on this post.

How do you assign a ref React?

Creating RefsRefs are created using React. createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

How do you do conditional rendering?

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.

How do you use REF in functional component React?

To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.


1 Answers

How about something Like this:

// directly assign the element to this.firstRef
// instead of doing it in the constructor
    <label
      ref={(elem) => (this.firstRef = elem)}
      style={{display: this.state.filterActive ? 'inline-block' : 'none'}}
    >
      Time Range
    </label>

and when using this.firstRef you put you work inside an if like this:

if (this.firstRef) {
// your work
}
like image 98
Akram Badah Avatar answered Nov 03 '22 01:11

Akram Badah