× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

A sample React application with central store and dummy components

Ivan Kurnosov
Sep 18, 2015
<pre><code class="language-javascript">import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = props; } addIngredient(id, recipe) { let recipes = [...this.state.recipes]; recipes[id].ingredients.push(recipe); this.setState({ recipes }); } render() { const actions = { addIngredient: this.addIngredient.bind(this) }; return ( &lt;Recipes recipes={this.state.recipes} actions={actions} /&gt; ); } } class Recipes extends Component { render() { const { actions } = this.props; const recipes = this.props.recipes.map((recipe, i) =&gt; &lt;Recipe recipe={recipe} key={i} id={i} actions={actions} /&gt;); return ( &lt;div&gt; {recipes} &lt;/div&gt; ); } } class Recipe extends Component { render() { const { recipe, actions, id } = this.props; return ( &lt;div&gt; &lt;h3&gt;{recipe.name}&lt;/h3&gt; &lt;Ingredients ingredients={recipe.ingredients} /&gt; &lt;IngredientForm actions={actions} id={id} /&gt; &lt;/div&gt; ); } } class Ingredients extends Component { render() { const { ingredients } = this.props; const list = ingredients.map((v, i) =&gt; &lt;li key={i}&gt;{v}&lt;/li&gt;) return ( &lt;ul&gt; {list} &lt;/ul&gt; ); } } class IngredientForm extends Component { constructor() { super(); this.state = { value: '' }; } handleSubmit(e) { e.preventDefault(); const { actions: { addIngredient }, id } = this.props; addIngredient(id, this.state.value); } handleChange(e) { this.setState({ value: e.target.value }); } render() { return ( &lt;form onSubmit={this.handleSubmit.bind(this)}&gt; &lt;input type="text" onChange={this.handleChange.bind(this)} value={this.state.value} /&gt; &lt;input type="submit" value="Add Ingredient" /&gt; &lt;/form&gt; ); } } const state = { recipes: [ { name: 'Chocolate Chip Cookies', ingredients: ['Chocolate Chips', 'Flour', 'Eggs'] }, { name: 'Hot Dogs', ingredients: ['Hot Dog', 'Bun', 'Mustard', 'Mayo', 'Ketchup'] } ] }; React.render(&lt;App recipes={state.recipes} /&gt;, document.getElementById('root')); </code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus