Home > Enterprise >  How can I send data from a child component to a parent of a parent of a parent (react)?
How can I send data from a child component to a parent of a parent of a parent (react)?

Time:01-10

I would like to send the synonym variable to my Dictionary.js component so that when I click on a button it will then use that word in my API call.

The components aren't directly linked. It's a child of a parent of a parent of a parent. Please refer to my open-sourced code.

I am aware of the need for a Callback function but I cannot get it to work .

export default function Synonyms(props) {
  function searchSynonym(event) {
    let synonym = event.target.innerHTML;
  }
  if (props.synonyms.length > 0) {
    return (
      <div className="Synonyms">
        <h4>Synonyms:</h4>
        {props.synonyms.map((synonym, index) => {
          if (index < 10) {
            return (
              <button
                type="button"
                
                key={index}
                onClick={searchSynonym}
              >
                {synonym}
              </button>
            );
          } else {
            return null;
          }
        })}
      </div>
    );
  } else {
    return null;
  }
}

You can find the full code on Github. Any help is much appreciated. Thank you!

CodePudding user response:

You can manage this scenario with props, but it is very nested. This is the time to use global state management. There are several options for managing state. You may use built-in state management tools like useContext and useReducer, or you can add dependencies like redux toolkit or another.

Check out the documentation to learn how to use usecontext! [https://reactjs.org/docs/hooks-reference.html#usecontext][1]

CodePudding user response:

The way to pass variables through many components simply (without implemented global state management) is stringing props through components for example:

import React from 'react'
const [synonym, setSynonym] = useState('')

const HighestLevelVarIsNeededComponent = () => {
    return (
        <>
            <MiddleLevel setSynonym={setSynonym}/>
            <div>{synonym}</div>
        </>
    )
}

export default HighestLevelVarIsNeededComponent

import React from 'react'

const MiddleLevel = (props) => {
    return (
        <>
            <LastLevel setSynonym={props.setSynonym} />
        </>
    )
}

export default MiddleLevel

import React from 'react'

const LastLevel = (props) => {
    // find synonym here
    let newSynonym = 'intersting'
    props.setSynonym(newSynonym)
    //after doing the above it will update the synonym variabile at the highest level
    return (
        <>
            <div></div>
        </>
    )
}

export default LastLevel
  •  Tags:  
  • Related