Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import logo from './logo.svg';
- import './styles/App.scss';
- import beers from './data/beers';
- function ListWrapper(props) {
- return (
- <ul>
- {props.items.map((item, index) => <ListItem handleClick={props.handleClick} key={`item_${index}`} item={item} />) }
- </ul>
- )
- }
- class ListItem extends React.Component{
- constructor (props) {
- super(props);
- this.selectItem = this.selectItem.bind(this);
- }
- selectItem () {
- console.log(this.props);
- this.props.handleClick(this.props.item.slug);
- }
- render() {
- return(
- <li onClick={this.selectItem}>{this.props.item.name}</li>
- )
- }
- }
- function NavWrapper() {
- return (
- <ul>
- <NavItem href="/" title="Home" />
- </ul>
- )
- }
- function NavItem (props) {
- return(
- <li>
- <a href={props.href}>{props.title}</a>
- </li>
- )
- }
- function ItemDetails(props) {
- return (
- <React.Fragment>
- <h1>{props.item.name}</h1>
- <p>{props.item.slug}</p>
- </React.Fragment>
- )
- }
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- selectedItem: null,
- items: beers
- }
- this.handleClick = this.handleClick.bind(this);
- }
- handleClick(itemSlug) {
- console.log('Hai cliccato ', itemSlug);
- const selectedItem = this.state.items.reduce((selectedItem, item) => {
- if (item.slug === itemSlug) {
- selectedItem = item;
- }
- return selectedItem;
- }, this.state.selectedItem);
- this.setState({
- selectedItem: selectedItem
- })
- }
- render() {
- return (
- <div className="App">
- <header className="App-header">
- <ListWrapper handleClick={this.handleClick} items={this.state.items} />
- <NavWrapper />
- </header>
- {this.state.selectedItem && <ItemDetails item={this.state.selectedItem} />}
- </div>
- );
- }
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement