JSFiddle - React, Tailwind, and code Playground
by Hyacinthe Hamon
HTML
<title>Products App</title>
<script src="https://fb.me/react-15.0.1.js"></script> <script src="https://fb.me/react-dom-15.0.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.0.0/react-redux.min.js"></script>
<body>
<div class="app"></div>
</body>
Babel + JSX
const initialState = [{
id: 0,
name: 'Product 1',
quantity: 0,
}, {
id: 1,
name: 'Product 2',
quantity: 0,
}]
function products(state = initialState, action) {
if (action.type == 'ADD_TO_CART') {
state[action.id].quantity += 1
return state
}
return state
}
const store = Redux.createStore(
Redux.combineReducers({ products })
)
function Header() {
return (
<span>
Number of items in cart:
{store.getState().products.reduce((productA, productB) => (
productA.quantity + productB.quantity
))}
</span>
)
}
function Product(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Quantity: {props.quantity}</p>
<button onClick={() => store.dispatch({
type: 'ADD_TO_CART',
id: props.id,
})}>Add to cart</button>
</div>
)
}
function App() {
return (
<div>
<Header />
{store.getState().products.map(product => (
<Product
id={product.id}
name={product.name}
quantity={product.quantity}
/>
))}
</div>
);
}
function render() {
ReactDOM.render(<App />, document.querySelector('.app'))
}
render()
store.subscribe(render)