v dřívějších tutorialech jsem si ukázali, jak pracovat s knihovnou React. Dnes si ukážeme práci se sesterskou knihovnou React Native, určenou pro tvorbu mobilních aplikací pro platformy iOS a Android. Protože set-up vývojového prostředí (instalace node.js, nastavení Xcode/Android studia) je zdlouhavý, ukážeme jak vytvořit aplikaci v React native for Web přímo v prohlížeči.
1) Import částí knihovny 2) Třída App 3) CSS styly 4) Výstup (aplikace)
Pokud jsme přidali produkt do košíku více než jednou, zvýšíme proměnnou cartItem.quantity o 1.
addToCart:function(item) { var found =false; var updatedCart =this.state.cart.map((cartItem) => { if (cartItem.name==item.name) { found =true; cartItem.quantity++; return cartItem; } else { return cartItem; } });
//if item IS NOT found, push product to cart w:/ quantity: 1 if (!found) { updatedCart.push({id:item.id, name:item.name, price:item.price, quantity:1}) } //update the cart component this.setState({ cart: updatedCart }); },
4 Cart class - switch between closed and opened state (add corresponding CSS classes)
var Cart =React.createClass({ getInitialState:function() { return { open:false } }, openCart:function() { this.setState({ open:!this.state.open }) }, //if the cart is opened, add the shadow to the cart box and fill it in with the data render:function() { return ( <div className={"Cart "+ (this.state.open?"Cart-Open":"")} onClick={this.openCart} > <p className="Title">Cart</p> <div> {this.props.cart.length>0?this.props.cart.map((item) => { return<p>{item.name}{item.quantity>1?<span> {item.quantity}</span>:''}</p> }) :<p>Empty</p>} </div> </div> ); } });
5 Render product (from JSON data above)
var Product =React.createClass({ addToCart:function() { this.props.addToCart(this.props.details); }, render:function() { let item =this.props.details; return ( <div className="Product" onClick={this.addToCart}> <p>{item.name}</p> <p>{item.price}</p> </div> ); } }); //Render the result ReactDOM.render(<App />, document.getElementById('app'));