React: designing for Data

React: designing for Data
0

#1

So my app has an api feeding it json data: lets say the data has several subsets that get passed down the react tree as props.
For example:
MyData:[
myFirstSubset:{
title: “string”,
anArray:[anObject{someValue:“string”}
]}],
mySecondSubset{etc,etc}]

I’m under the impression this would all be held at the top of the data tree as state?
As you can see each subset can have an array with several objects , each object can hold someValue which is a string.
Now I can send that down as props, that’s easy enough. What if I change the value of someValue and try and write it back upstream, how do I retain all the array indices to target the correct value (coming from angular frame of mind) can you just pass the index back some way?


#2

My personal way of dealing with this is to give the elements that are rendered using an iterator like map an id which contains the i value of the element from the array with an underscore before it (e.g. id={"myButton_" + i}. The id value can be propagated back up when a corresponding element is clicked via an onClick function and its event object. You can then access the i value in the handleClick(event) function you setup using index = event.target.id.split('_')[1]. After, make a copy of the state object and change the relevant part of it using this index value. You can use the splice function if you are inserting or deleting. You can then setState with the new copy of the state object.


#3

Cool, thankyou for the feedback. Makes sense, In my search for answers ayesterday I came across a really cool medium article on react structuring- check it out: https://hackernoon.com/fractal-a-react-app-structure-for-infinite-scale-4dab943092af , I haven’t used redux yet but it sounds good!..


#4

Thanks for the link. Sounds like the fractal technique would be very useful on large projects. Redux is worth learning. It provides a single state that any React component can access and change. It prevents the need to pass state down via props like you do in React. It does involve writing a fair bit of extra code though, so for simple apps with a small component tree, using React by itself is probably the way to go.