I need to know how to update a data object based on a button click. This data object is being passed into a Child Component. When a user chooses an option in the dropdown menu, I want to populate that data object based on the key of the chosen option in the dropdown menu.
Here is my Parent Component...
<div>
<Dropdown>
<DropdownTrigger>
<Button variant="bordered">
Films
</Button>
</DropdownTrigger>
<DropdownMenu
variant="faded"
aria-label="Dropdown menu with description"
>
<DropdownSection title="Shorts">
{films.shorts.map((film) => (
<DropdownItem
key={film.key}
textValue={film.key}
onAction={(key) => showFilm(key)}
>
{film.name} {film.year}
</DropdownItem>
))}
</DropdownSection>
</DropdownMenu>
</Dropdown>
{shown && <Film data={data} />}
</div>
My Child Component is <Film>. I am passing the data object into it.
I'm calling the function showFilm(key) when an option is clicked in the dropdown menu.
What I need to know is how do I get the Child Component to update with new data if I update that data in the showFilm() function?
I tried updating the data object when the showFilm() function is called, but the Child Component doesn't receive the updated data. I need the Child Component to be refreshed so it receives the new data object (that has been updated).
const [shown, setShown] = useState(false);
let data;
function showFilm(key) {
setShown(true)
// here is where I want to update the data object being passed into the Child Component. I want the data object to equal the key of the option that was clicked.
data = key;
console.log("data", data, "key", key)
}
define a state in order to store data in it and pass state to child component !!notice that when state changes in parent component, both child and parent components are re-render as well.
const [data, setData] = useState([]);
function showFilm(key) {
setShown(true)
data = key;
console.log("data", data, "key", key)
setData(key);
}
pass data to child component
{shown && <Film data={data} />}