0

If I have multiple divs whose are rendered from data array using array.map() method like that:

    import React,{ ReactDOM } from 'react'
    import { useState,useEffect,useRef } from 'react'
    import getResults from '../api/getResults'
    ...
    function Results (props){
      const [results,setResults]=useState([])
      useEffect(()=>{
      setResults(getResults(props.season))},
      [props.season])
    return (
    {results.map((elem,index)=>{
       return (            
        <div key={index} onClick={()=/*what should I do to render inside this div?*/>}>{elem}</div>
       )
        })}
        <Details/> //I want to render this jsx inside the clicked div
      )
       ........
      }

How to get reference of specific clicked div to render Details jsx component inside this div? I tried use useRef hook but it always return the last div.

0

1 Answer 1

1

Track the clicked element in state. For example, consider this state value:

const [clickedElement, setClickedElement] = useState();

By default the value is undefined. You can update the value to some identifier when clicking one of the elements:

<div key={index} onClick={() => setClickedElement(index)}>{elem}</div>

Now each click updates state indicating which element was clicked.

Then you can use that state value to determine what to render. For example:

<div key={index} onClick={() => setClickedElement(index)}>
  {elem}
  {clickedElement === index ? <Details/> : null}
</div>

Basically any way you approach it, the structure is pretty much always the same:

  1. Track information in state.
  2. Events (e.g. a click event) update state.
  3. UI is rendered based on state.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.