React Advice Needed: Recipe Box challenge

React Advice Needed: Recipe Box challenge
0

#1

Hi all, I’m looking for some advice on best practices in React.

I’m on the recipe box challenge and currently storing my recipes as an array of recipe objects in state:
this.setState({
recipes: [{name: ‘lasagna’, ingredients: [‘pasta’, ‘cheese’, ‘sauce’]}]
})

However, I need to toggle display of ingredients when a user clicks on the recipe’s name. I’m unsure whether to store this as an a boolean key/value pair in each recipe object. It seems a little burdensome to update the value of each recipe due to immutability of state. (https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c)

I guess another option is to store state in a Recipe component but this seems to violate the principle of data flow within react. From what I’ve read it seems better to store state in the most senior parent component and then hand down state as props to the children for rendering. Any advice would be much appreciated!!


#2

Hey @jonathanwmaddison I’ll do my best to give a little help here, but I am immersed in learning react as well. In order to toggle the display of the ingredients, you may want to do some searching on your favorite front end framework (like bootstrap, foundation, etc…) and “accordion”. Or “collapse”. When I did my recipe box, I also wondered how I was going to manage all of the collapsing/expansion, but then I realized this is a built in feature to many frameworks.

Hint: I even noticed there is one set up to work with React, although this is not the one I used.

In terms of state and the recipes, I was able to keep my main component as the only smart component using state, and all the data passed down as props to the other components. As I have started looking at Redux, yes this is the way it seems to work. The blog post you provided talks about making sure you make a copy of state, altering that copy, and then using this.setState to update state. As long as you are doing it this way, you shouldn’t be mutating state itself.

By the way, thanks for posting, because I now realize that I was mutating state without even realizing it. Oops.


#3

That’s a great suggestion! Thank you. I was trying to do everything with React…and forgot about everything else I’ve learned…oops :slight_smile: