Home > OS >  How to access parent props from child component - react
How to access parent props from child component - react

Time:11-02

Let's say that I want to build a reusable react Accordion Component, which will have an AccordionSummary and an AccordionDetails child like this:`

<Accordion>
 <AccordionTitle>This is an accordion title</AccordionTitle>
 <AccordionSummary>This is the accordion summary, which will be shown if the user clicks the accordion title </AccordionSummary>
</Accordion>

How can I make it, so that when the AccordionTitle is clicked, the summary will be shown to the corresponding accordion. Is there a way to share data between react child and parent components for each individual accordion in this case.

CodePudding user response:

You can use a context here. Sorry for promoting, but I wrote a detailed article on this topic : https://rocambille.github.io/en/2022/05/02/how-to-do-a-modal-in-react-the-html-first-approach/

This could lead to something like that for your Accordion:

const AccordionContext = createContext();

function Accordion({ children }) {
  const [someState, setSomeState] = useState();

  return (
    <AccordionContext.Provider value={ { someState, setSomeState } }>
      {children}
    </AccordionContext.Provider>
  );
}

function AccordionTitle({ children }) {
  const { someState, setSomeState } = useContext(AccordionContext);

  return (
    ...
  );
}

function AccordionSummary({ children }) {
  const { someState, setSomeState } = useContext(AccordionContext);

  return (
    ...
  );
}

But as stated in my article, you may want to consider HTML stuff like the summary/details tags ;)

  • Related