Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import React from 'react';
  2. import logo from './logo.svg';
  3. import './styles/App.scss';
  4. import beers from './data/beers';
  5.  
  6. function ListWrapper(props) {
  7. return (
  8. <ul>
  9. {props.items.map((item, index) => <ListItem handleClick={props.handleClick} key={`item_${index}`} item={item} />) }
  10. </ul>
  11. )
  12. }
  13.  
  14. class ListItem extends React.Component{
  15. constructor (props) {
  16. super(props);
  17. this.selectItem = this.selectItem.bind(this);
  18. }
  19.  
  20. selectItem () {
  21. console.log(this.props);
  22. this.props.handleClick(this.props.item.slug);
  23. }
  24.  
  25. render() {
  26. return(
  27. <li onClick={this.selectItem}>{this.props.item.name}</li>
  28. )
  29. }
  30. }
  31.  
  32. function NavWrapper() {
  33. return (
  34. <ul>
  35. <NavItem href="/" title="Home" />
  36. </ul>
  37. )
  38. }
  39.  
  40. function NavItem (props) {
  41. return(
  42. <li>
  43. <a href={props.href}>{props.title}</a>
  44. </li>
  45. )
  46. }
  47.  
  48. function ItemDetails(props) {
  49. return (
  50. <React.Fragment>
  51. <h1>{props.item.name}</h1>
  52. <p>{props.item.slug}</p>
  53. </React.Fragment>
  54. )
  55. }
  56.  
  57.  
  58. class App extends React.Component {
  59. constructor(props) {
  60. super(props);
  61. this.state = {
  62. selectedItem: null,
  63. items: beers
  64. }
  65. this.handleClick = this.handleClick.bind(this);
  66. }
  67.  
  68. handleClick(itemSlug) {
  69. console.log('Hai cliccato ', itemSlug);
  70. const selectedItem = this.state.items.reduce((selectedItem, item) => {
  71. if (item.slug === itemSlug) {
  72. selectedItem = item;
  73. }
  74. return selectedItem;
  75. }, this.state.selectedItem);
  76.  
  77. this.setState({
  78. selectedItem: selectedItem
  79. })
  80. }
  81.  
  82. render() {
  83. return (
  84. <div className="App">
  85. <header className="App-header">
  86. <ListWrapper handleClick={this.handleClick} items={this.state.items} />
  87. <NavWrapper />
  88. </header>
  89. {this.state.selectedItem && <ItemDetails item={this.state.selectedItem} />}
  90. </div>
  91. );
  92. }
  93. }
  94.  
  95. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement