Sunday, October 4, 2020

Search for users, example for form,event and binding

 

//Search.js
import React, { Component } from 'react'

export class Search extends Component {
    state={
        text:''
    }
    
    //if we don't use arrow function then we need to bind this/event object to the function explicitly
    onSubmit(e){
        e.preventDefault();
        console.log(this.state.text);
    }

    onChange = (e) =>{
        this.setState({text: e.target.value});
        //or we can type//this.setState({[e.target.name]: e.target.value});
    }
    render() {
        return (
            <div>
                <form onSubmit={this.onSubmit.bind(this)} className="form">
                    <input 
                    type="text" 
                    name="text" 
                    placeholder="Search Users..." 
                    value={this.state.text}
                    onChange={this.onChange}
                    />
                    <input type="submit" value="Search" className="btn btn-dark btn-block"/>
                </form>
            </div>
        )
    }
}

export default Search

//App.js
import React,{Component} from 'react';
import logo from './logo.svg';
import Navbar from './components/layout/Navbar';
import Users from './components/users/Users';
import Search from './components/users/Search';
import axios from 'axios';
import './App.css';

class App extends Component {
  state={
    users:[],
    loading:false
  }


//npm i axios
async componentDidMount(){
 this.setState({loading: true});
 //axios.get('https://api.github.com/users').then(res => console.log(res.data));
 const res = await axios.get(`https://api.github.com/users?client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);;

 //console.log(res.data);
 this.setState({users: res.data,loading:false});
 
}

  render(){
    return(
      <div className="App">
        <Navbar/>
        <div className='container'>
        <Search />
        <Users loading={this.state.loading} users={this.state.users}/>
        </div>
        
      </div>
    );
  }
  
}

export default App;

Repo commit

No comments:

Post a Comment