I have a data array that I am mapping onto a material-ui Typography.
{
array.map((item, id)=> <Typography key={id} value={item.name} />)
}
The code displays the typography with their respective values on the browser as expected, however, I am trying to set the mapped value of Typography into a state like this...
const [data, setData] = useState();
...
{
array.map((item, id) =>
<Typography key={id} value={item.name} {(e)=>setData(e.target.value)} />
)}
This method does not work.
How do I make data to be the value of <Typography/>
If I understand correctly, you're trying to store item.name within local state? How are you receiving the data that you are mapping through?
Are you trying to store each item you're mapping through and represent key-value pairs of an object within local state? What are you trying to do with the state once you have it?
As far as I know, there's is no way to assign values to local state while you are mapping through an array. However, there are multiple ways to assign the data to local state outside of the return.
Also, what is this line doing?
{(e)=>setData(e.target.value)}
It seems you're trying to create a controlled input on a Typography component without an onChange prop, as well as on a component that does not take input.
One more aside, although it is not a big deal -
{
array.map((item, id) =>
<Typography key={id} value={item.name} ..../>
)}
id here is usually referred to as index
Edited for answer
I normally use Redux to manage the global state, but the process should be the same for Context Provider:
const yourComponent = () => {
const [data, setData] = useState();
// This is the array you get from the Context Provider
const yourArray = getArrayFromContextProvider();
useEffect(() => {
// If you want to normalize the array data
if (yourArray) {
const dataObj = {};
yourArray.forEach((item, index) => {
// Make the key unique by using the item id OR you can use index
dataObj[item.id] = item;
// OR you can add the item value as the key
dataObj[item.value] = item;
});
setData(dataObj);
}
// If you just want to store the array
if (yourArray) {
setData(yourArray)
}
}, [yourArray]);
return <div>
{/* ...Your map */}
</div>;
};
export default yourComponent