React tutorial / exercise

illustrating different ways of doing almost the same thing

by jonahe

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 0 10px;
  list-style-type: circle;
}

React

const FruitListItem = props => {
	return (
  	<li>
      <b>{props.name}:</b><span>{props.price} SEK</span>
    </li>
   );
}

function getSimpleFruitItem(fruitName) {
	return <li>{fruitName}</li>;
}

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    	fruits: [
      	{ name: "Apple", price: 400 },
        { name: "Banana", price: 500 },
      ]
  	}
  }
  
  render() {
    return (
      <div>
      
        <ul className="first">
          <li>apple</li>
          <li>banana</li>
        </ul>
        <hr/>
        
        <ul className="second">
          {
            [
              <li>apple</li>, 
              <li>banana</li>
            ]
          }
        </ul>
        <hr/>
        
        <ul>
          {
            [
              getSimpleFruitItem("apple"),
              getSimpleFruitItem("banana"),
            ]
          }
        </ul>
        <hr/>
        
        <ul>
          {
          	["apple", "banana"]
            	.map(fruit => <li>{fruit}</li>) 
          }
        </ul>
        <hr />
        
        <ul>
          {
          	this.state.fruits
            	.map(fruitObj => <FruitListItem name={fruitObj.name} price={fruitObj.price} />)
          }
        </ul>
        <hr/>
        
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))