Answer the question
In order to leave comments, you need to log in
React. How to pass updated state on change in child component?
const getAllLists = () => {
const data = [
{
id: 1,
title: "The Vines",
wrapped: false
},
{
id: 2,
title: "AURORA",
wrapped: false
},
];
return data;
};
import React, { useState, useEffect } from "react";
import { getAllLists } from '../api';
import { List } from "./List";
export const Lists = () => {
const [lists, setLists] = useState([]);
useEffect(() => {
const fetchLists = async () => {
const data = await getAllLists();
setLists(data);
};
fetchLists();
}, []);
const setWrapped = id => {
const data = lists;
const idx = data.findIndex(i => i.id === id);
data[idx].wrapped = !data[idx].wrapped;
console.log(data[idx]);
setLists(data);
};
return (
<>
{lists.map(list => (
<List key={list.id} list={list} setWrapped={setWrapped}>{...}</List>
))}
</>
);
}
import React from "react";
export const List = ({ list, children, setWrapped }) => {
const { id, title, wrapped } = list;
return (
<div className="list">
<div className="list-top">
<h1>{title}</h1>
<button onClick={() => setWrapped(id)}>Click</button>
</div>
{!wrapped && (
<div className="cards">
{children}
</div>
)}
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question