How to use ref in (conditional render) How to use ref in (conditional render) reactjs reactjs

How to use ref in (conditional render)


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}


I was facing the same problem but I'm using hooks. I found an alternate solution. By using Intersection Observer, we can solve it.

In Hooks, use 'useInView' hook from 'react-intersection-oberserver',

// Use object destructing, so you don't need to remember the exact order

const { ref, inView, entry } = useInView(options);

// Or array destructing, making it easy to customize the field names

const [ref, inView, entry] = useInView(options);

Attach 'ref' to your DOM node, 'inView' will return a boolean whether your DOM node is in View or not and 'entry' will give access to DOM node properties.

import React from 'react';import { useInView } from 'react-intersection-observer'; const Component = () => {  const { ref, inView, entry } = useInView({    /* Optional options */    threshold: 0,  });   return (    <div ref={ref}>      <h2>{`Header inside viewport ${inView}.`}</h2>    </div>  );};

This fixed my problem.

For class based components, read here: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API


try this,

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