0

I am new using react.

I'd like to add REF in my component only if it is not null.

  if (posts.length === index + 1) {
        number = post.id;
        return <Post key={post.id} id={post.id} ref={lastPostElementRef} titulo={post.titulo} />
    }
    else {
        return <Post key={post.id} id={post.id} titulo={post.titulo} />
    }

if it is the last post it should add a ref on it. The others will not got this ref val.

so I try:

const Post = React.forwardRef((props, ref) => (

    <div 
        className={classes.post} 

//if (ref != null) ???
        ref={ref} >

        data-id: {props.id}
        titulo: {props.titulo}

    </div>

));

export default Post;

how can I check if ref is not null inside my JSX to add or not the ref={ref} value inside my div?

RGS
  • 4,062
  • 4
  • 31
  • 67

1 Answers1

1

If no ref is passed to your Post component, then ref would just be undefined, so the div's you don't want to get ref, will get ref={undefined}. This works as you want it to.

However, you can also explicitly check for the ref in a ternary operator: ref ? ref : undefined or ref != null ? ref : undefined, but that is just longer than it has to be (unnecessary).

PS: You don't want to explicitly check for null because you never set the ref to be null, but you also don't want to use the != operator as that will implicitly convert undefined into null. When comparing in javascript, you should use !== or ===, but then it won't be true when ref is undefined, because undefined won't be converted into null. In a way, your intended syntax is doing 2 things poorly which gives you the intended outcome.

More info on === vs == here.

Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167