React

by Pranab Dey

HTML

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

CSS

.myList{
  display: inline-block;
  padding: 0 8px;
}
.myList:not(:last-child){
  border-right: 1px solid #333;
}

React

class Make extends React.Component {
  constructor(newProps) {
    super(newProps)
    this.nameRef = React.createRef();
    this.nameUpdateRef = React.createRef();
    this.name = this.props.name;
    this.grade = "B1";
    this.state = {
    	name: this.props.name,
      persons: []
    };
    //this.updateName = this.updateName.bind(this);
  }
  
  /* componentDidMount(){
    fetch('https://randomuser.me/api/?results=2')
    .then(data=>data.json())
    .then(data=>this.setState({
      persons: data.results
    }))
  } */
  randomNameUpdate(){
  	fetch('https://randomuser.me/api/?results='+this.nameUpdateRef.current.value)
  	    .then(data=>data.json())
  	    .then(data=>{
        	this.setState({
  	      	persons: data.results
  	    	})
        }
        )
  }
  
  updateName(){
  //var nameValue = document.querySelector("input[type=text]");
  	return(
    	this.setState({
    		name: (this.nameRef.current.value===''? this.props.name:this.nameRef.current.value)
    	})
    )
  }
  
  render() {
    return (
      <div>
        <h2>Hi there,</h2>
        <input type="text" ref={this.nameRef}/>
        <button className="btn" onClick={this.updateName.bind(this)}>Change name</button>
        <p>My name is {this.state.name} &amp; grade is {this.grade}</p>
        <hr/>
        <p>How many profiles you want to see below, type that number in the input box - </p>
        <input type="text" className='randomNamesNum' ref={this.nameUpdateRef} onChange={this.randomNameUpdate.bind(this)}/>
        <br/>
        <div className="personList">
          {this.state.persons.map(d=>{
             return(
             	<div className="myList" key={d.login.salt}>
              <img src={d.picture.medium} alt={`id is ${d.login.salt}`}/>
               <p className="name">{d.name.first} {d.name.last}</p>
               <span className="gender">{d.gender}</span>
             </div>
             )
          })}
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Make...