I have an API call via a local JSON file in the child component.
In the parent component I want to have something like this:
<ComponentA value={test} />
In my component with the API call I want to do the following:
{DataFromJson.test.map(a => a)}
Data in json is in the following format:
{test:[{value: 1}], test2:[{value:2}]}
So that test is a value that is appended to DataFromJson (and whenever a value is passed to the component test
changes to whatever value).
Is there a workable solution around this?
You could use an useEffect
to listen for changes in props passed in:
import React, { useEffect, useState } from "react";
import Data from "./data.json";
const Info = (props) => {
const [dataJson, setDataJson] = useState(Data);
useEffect(() => {
// useEffect to listen for changes in props.value
// Update data here using `setDataJson()`
}, [props.value]);
return <div>{/* Display */}</div>;
};
export default Info;
Actually i think you are trying to access the value dynamically. You want to pass a value from the parent and see the result in child component accordingly. If i'm right about this. Then you need to use {dataJson[props.value].map((a) => a.value)}
to get that data dynamically.
If you pass <Info value="exampleTwo" />
then the output will show test2
If you pass <Info value="exampleOne" />
then the output will show test
And to update you can use
useEffect(() => {
setDataJson((prevData) => ({ ...prevData, ...newData }));
}, [newData]);
I've added the update code in the codesandbox link.
Here is the working solution codesandbox-link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.