The ideal result is displaying strings when items in the list are clicked.
Here's the Root Component.
const App = () => {
const [click, setClick] = useState(null);
const handleClick = name => {
setClick(name);
};
return (
<div>
<Parent handleClick={handleClick} />
{click && <p>{click} is clicked.</p>}
</div>
);
};
and Parent Component.
const Parent = ({ handleClick }) => (
<div>
<Child
name="First Item"
handleClick={handleClick("First Item is Clicked!")}
/>
<Child
name="Second Item"
handleClick={handleClick("Second Item is Clicked!")}
/>
<Child
name="Third Item"
handleClick={handleClick("Third Item is Clicked!")}
/>
</div>
);
and Child Component.
const Child = ({ name, handleClick }) => <li onClick={handleClick}>{name}</li>;
Also, the code sandbox link.
I just wondered why the result never is never changed by click.
Problem is that you aren't passing a function to handleClick
instead an evaluated value from parent. You code must be
import React from "react";
import Child from "./Child";
const Parent = ({ handleClick }) => (
<div>
<Child
name="First Item"
handleClick={() => handleClick("First Item is Clicked!")}
/>
<Child
name="Second Item"
handleClick={() => handleClick("Second Item is Clicked!")}
/>
<Child
name="Third Item"
handleClick={() => handleClick("Third Item is Clicked!")}
/>
</div>
);
export default Parent;
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With