I’m trying to render the selected li (mapped in a child component) in an another child component. So you have the following structure (very simple):
Parent Component (Parent.JS)
- ➥ First Child called Title.JS (that should render the title selected from the Second Child, which will contain the menu)
- ➥ Second Child called Menu.JS (which contains the menu)
The exercise I’m trying to do and to understand here, is how to pass data(s) between children using props (in case the value goes through the parent).
Parent.JS
import React, { useState } from 'react' import Child from './Child' import Title from './Menu' function Parent() { const [word, setWord] = useState('Parent'); return ( <div> <Title /> <Menu changeWord={word => setWord(word)}/> </div> ) } export default Parent
Title.JS
import React from 'react' function Title(props) { return ( <div> //Here I tell the code to print "Nothing selected" //until I don't choose a link in the menu. {props.title ? <h1>{props.title}</h1> : <h1>Nothing selected</h1>} </div> ) } export default Title
Menu.JS
import React from 'react' const data = [ {title: "Home"}, {title: "About"}, {title: "Contact"}, ] function Menu(props) { return ( <div> {data.map((item) => { return <li onClick={() => props.changeWord(props.children)}>{item.title}</li> })} </div> ) } export default Menu
Of course, App,JS is simplified.
import Parent from './Parent' function App() { return ( <div> <Parent /> </div> ); } export default App;
I’m so close..
Advertisement
Answer
When you call changeWord
you want to pass the item
you’re mapping through as opposed to props.children
So your Menu
should look like this
import React from 'react'; const data = [{ title: 'Home' }, { title: 'About' }, { title: 'Contact' }]; function Menu(props) { return ( <div> {data.map((item) => { return <li onClick={() => props.changeWord(item)}>{item.title}</li>; })} </div> ); } export default Menu
Your Parent
should pass the word.title
state value into the Title
like this
import React, { useState } from 'react' import Child from './Child' import Title from './Menu' function Parent() { const [word, setWord] = useState('Parent'); return ( <div> <Title title={word.title}/> <Menu changeWord={word => setWord(word)}/> </div> ) } export default Parent
NB: You should remove your initial state value of 'Parent'
because word
is an object now and you may get an error when trying to access word.title
.