React: how to edit parent state when child prop changes, parent state is a list

I am working on the Recipe Box challenge and I need some help figuring out how to get a child component to talk to a parent, specifically editing props passed to a child, and having those changes saved to a parent.

here is my structure.

   <RecipeContainer>
      <RecipeList> <-- Recipes stored here as a list. (stored in state)
         <Recipe>
            <RecipeView></RecipeView> <!-- A recipe can be edited here. (passed by prop)
         </Recipe>

         <Recipe>
            <RecipeView></RecipeView>
         </Recipe>

         <Recipe>
            <RecipeView></RecipeView>
         </Recipe>
      </RecipeList>
   </RecipeContainer>

holds a list of recipes and the component is generated accordingly, and one recipe is passed as a prop.
is like a modal window, here the user has a change to edit the recipe text.

The problem is that a child cannot edit a prop and have it propagate via a parent.

Here is some of the code I am working on: http://codepen.io/Jon1701/pen/BzJqjR

You have to pass a callback as a prop to the child which is capable of editing the original state.

So for example you might pass props such as recipe (the data itself from state) and editRecipe (a function that lives in the parent component capable of modifying the state).

<EditRecipe recipe = {this.state.recipe} editRecipe = {this.editRecipe} />

(Note that if using ES6 you will have to explicitly bind this to editRecipe, e.g. in the constructor function by saying this.editRecipe = this.editRecipe.bind(this))

You would then have editRecipe defined as a function within the parent component which modifies the recipe in state. You can pass data back up along with this function from the prop by binding it. For example, in the child component where you use this function you could say something like:

<button onClick = {this.props.editRecipe.bind(this, recipeTitle)}>Edit the Recipe</button>

Assuming you have recipteTitle defined there (probably from a prop from the parent). Basically, this is how you can modify state from child components, by passing a callback to the child which is responsible for the modifications to state.

I think this design is very good because your state lives in one component along with all the functions that may modify it.

2 Likes