React.js Basics

Learn the basics about React.js

by Mingtao Sun

HTML

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>

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

<!-- 
  1) Create a <div> and render a base component with React
  2) Output an array of hobbies in this <div> (provide some default hobbies)
  3) Add a 'New Hobby' button + <input> field where you add the hobby the user entered to the list
  4) Make the hobbies clickable to remove them once clicked
  5) Add a <p>Hobby deleted!</p> which is only shown once at least one hobby was deleted (be creative on how to track this!)
  6) Add a hobby counter (<p>Hobbies: ...</p>) above the list of hobbies
  7) Dynamically style/ add classes to the hobby counter, depending on whether you have more or less than 3 hobbies
  8) Outsource your hobbies (the <li> elements) into a re-usable component
-->

CSS

.many {
  background-color: blue
}

Babel + JSX

function Hobby(props){
	return (
  	<li key={props.name} onClick={() => {props.hobbyClickedHandler(props.name)}}>{props.name}</li>
  );
}

class App extends React.Component{
	
  constructor(props){
  	super(props);
    this.state={
    	hobbies: ['book', 'movie'],
      newHobby: '',
      hobbyDeleted: false
    };
  }
  
  addHobby(){
  	const oldHobbies = this.state.hobbies;
    var hobby = this.state.newHobby; 
    this.setState({
    	hobbies: oldHobbies.concat(hobby),
      newHobby: ''
    });
  }
  
  changeHobby(event){
  	this.setState({
    	newHobby: event.target.value
    });
  }
  
  removeHobby(hobby){
    const oldHobbies = this.state.hobbies;
    this.setState({
    	hobbies: oldHobbies.filter(el => el != hobby),
      hobbyDeleted: true
    });
  }
  
  render() {
  	let hobbyList = this.state.hobbies.map(
    	(el) => {
      	return <Hobby name={el} hobbyClickedHandler={this.removeHobby.bind(this)}/>
      }
    );
    let hobbyDeletedMessage = this.state.hobbyDeleted ? 'Hobby deleted!' : '';
    let manyHobbyClass = this.state.hobbies.length > 3 ? 'many' : '';
    return (
    	<div>
        <h1>Hello World!</h1>
        <input id="hobby" value={this.state.newHobby} onChange={this.changeHobby.bind(this)}/>
        <button onClick={this.addHobby.bind(this)}>Add hobby</button>
        <p className={manyHobbyClass}>Hobbies: {this.state.hobbies.length}</p>
        <ul>
          {hobbyList}
        </ul>
        <p>{hobbyDeletedMessage}</p>
      </div>
    );
  }
  
}

ReactDOM.render(<App />, document.getElementById('app'));