If I have an object key values that we assume change due to some input. How do I update the child component that takes those values and displays them. When I send the values as props to the child component they obviously don't update and stay as the initial value set in tempData. So how would I prompt the child props to resend or update?
I already have functions that fetch the data and put it all into its places in the tempData object. Am I going about this wrong by setting the data in an Object?
const Parent = () => {
const tempData = {
location: "",
weather: "",
temperature: "",
};
return (
<>
<System onChange={(value) => urlHandler(value)} />
<City onChange={(value) => setCity(value)} />
<Data
location={tempData.location}
weather={tempData.location}
temperature={tempData.temperature}
/>
</>
};
const Child = (props) => {
return(
<>
<div>location: {props.location}</div>
<div>temperature: {props.temperature}</div>
</>
)
};
React has no way to detect that you have mutated tempData
so it won't re-render the element with the new data.
Store the data in the state instead. Using the state API to update the state will trigger a re-render.
This is covered in the React tutorial but that focuses on old-style class components. Modern code would use the useState
hook in a function component instead. This is also covered by the MDN React tutorial.