Calling a function and pass data from custom component to calling App.js
This concept is shown in the below code.
//Search.js import React, { Component } from 'react' import PropTypes from 'prop-types'; export class Search extends Component { state={ text:'' } static propTypes={ searchUsers: PropTypes.func.isRequired,//ptfr shortcut } //if we don't use arrow function then we need to bind this/event object to the function explicitly onSubmit(e){ e.preventDefault(); //a way to send props back to App.js this.props.searchUsers(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 } //Search github users //query gathered from developer.github.com/v3/search searchUsers = async text =>{ this.setState({loading: true}); const res = await axios.get( `https://api.github.com/search/users?q=${text}?client_id=${ process.env.REACT_APP_GITHUB_CLIENT_ID }&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}` ); this.setState({users: res.data.items,loading:false}); } render(){ return( <div className="App"> <Navbar/> <div className='container'> <Search searchUsers={this.searchUsers} /> <Users loading={this.state.loading} users={this.state.users}/> </div> </div> ); } } export default App;
No comments:
Post a Comment