react assignment udemy

react assignment udemy

by Yashpreet Singh

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>

Babel + JSX

class App extends React.Component{
		constructor(props){
    		super(props);
         this.state = {
           hobbies:[],
           newHobby:'',
           counter:0
        };
    }
    addNewHobbyInput(event){
   			this.setState({
      		newHobby:event.target.value
        });
    }
    deleteHobby(hobby){
       const oldList = this.state.hobbies;
       const position = oldList.indexOf(hobby);
       let newList = oldList.filter(
           		(el,index) => {return (index != position)}
       );
       this.setState({
      		 hobbies:newList,
           newHobby:'',
           counter:newList.length
       });
       alert("here");
    }
    addHobbyToList(){
      let newHobby = this.state.newHobby;
      if(newHobby && newHobby.length >0){
    	  const oldList = this.state.hobbies;
         let newList = oldList.concat(this.state.newHobby);
         this.setState({
      		 hobbies:newList,
           newHobby:'',
           counter:newList.length
         });
      }
    }
    render(){
        let list = '';
    		if (this.state.hobbies) {
          list = this.state.hobbies.map(
            (el,index) =>{
            		const liStyle = {
        						backgroundColor:index%2 == 0?"red":"green"
        				};
                return <li key={index} style={liStyle} onClick={
                () =>{this.deleteHobby(el)} }>{el}</li>
            }
          );
        }
        return (<div>
            {list}
            <p>No of Hobbies are: {this.state.counter}</p>
           <input type="text" value={this.state.newHobby} onChange={this.addNewHobbyInput.bind(this)}></input>
           <button onClick={this.addHobbyToList.bind(this)}> Add</button>
        </div>);
    }
}
ReactDOM.render(<App />,document.querySelector('#app'));