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.
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With