title: Conditionally assign ref in react
body: <p>I'm working on something in react and have encountered a challenge I'm not being able to solve myself. I've searched here and others places and I found topics with similar titles but didn't have anything to do with the problem I'm having, so here we go:</p>
  <p>So I have an array which will be mapped into React, components, normally like so:</p>
  <pre><code>export default ParentComponent = () =&gt; {
  
  //bunch of stuff here and there is an array called arr
  
  return (&lt;&gt;
   
      {arr.map((item, id) =&gt; {&lt;ChildComponent props={item} key={id}&gt;})}
  
  &lt;/&gt;)
  
  }
  </code></pre>
  <p>but the thing is, there's a state in the parent element which stores the id of one of the ChildComponents that is currently selected (I'm doing this by setting up a context and setting this state inside the ChildComponent), and then the problem is that I have to reference a node inside of the ChildComponent which is currently selected. I can forward a ref no problem, but I also want to assign the ref only on the currently selected ChildComponent, I would like to do this:</p>
  <pre><code>export default ParentComponent = () =&gt; {
  
  //bunch of stuff here and there is an array called arr and there's a state which holds the id of a  selected ChildComponent called selectedObjectId
  
  const selectedRef = createRef();
  
  return (&lt;&gt;
      &lt;someContextProvider&gt;
      {arr.map((item, id) =&gt; {
         &lt;ChildComponent 
          props={item} 
          key={id} 
          ref={selectedObjectId == id ? selectedRef : null}
         &gt;
      })}
     &lt;someContextProvider /&gt;
  &lt;/&gt;)
  
  }
  </code></pre>
  <p>But I have tried and we can't do that. So how can dynamically assign the ref to only one particular element of an array if a certain condition is true?</p>