Search code examples
javascriptreactjsstatereact-props

How to prop an input value into a parameter for an API call


I have a Header.js component that takes a user's input and updates its state. I want to transfer(prop?) this item into the parent component App.js where it will be put in as a parameter and the data will be console logged relative to the user's input. I don't know how to transfer the state and implement it into the API's parameter.

class Header extends Component {
  constructor() {
    super();
    this.state = {
      query: '',
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    // form's input value
    let userSearch = this.state.query;
  }

  handleChange = (e) => {
    this.setState({
      query: e.target.value
    });
  }

  render() {
    return (
      <header>
        <form onSubmit={this.handleSubmit}>
          <input 
            onChange={this.handleChange} 
            type="text" 
            placeholder="Search"
          />
          <label className="sr-only" htmlFor="search">Search News</label>
        </form>
      </header>
    )
  }
}

export default Header


import Header from './Components/Header'
import axios from 'axios';


class App extends Component {
  constructor() {
    super();
    this.state = {
      articles: [],
    }
  }

  componentDidMount() {
    axios({
      // I want this.state.query in header.js to be {parameter}
      url: 'http://newsapi.org/v2/everything?q={parameter}&sortBy=popularity&apiKey=where-the-key-goes',
      method: 'GET',
      responseType: 'JSON',
    }).then((response => {
      let articles = response.data.articles;
      this.setState({
        articles,
        isLoading: false,
      })

      console.log(articles);
    }))
  }

  render() {
    return (
      <>
        <Header />
      </>
    )
  }
}

export default App

Solution

  • You could create a callback function in the App component and pass to Header as a prop:

    class App extends Component {
    
      ...
    
      handleSearch = (value) => {
        axios({
          url: `http://newsapi.org/v2/everything?q=${value}&sortBy=popularity&apiKey=where-the-key-goes`,
          method: "GET",
          responseType: "JSON",
        }).then((response) => { ... });
      };
    
      render() {
        return (
          <>
            <Header handleSearch={this.handleSearch} />
          </>
        );
      }
    }
    

    Then use it in the Header's handleSubmit function:

    handleSubmit = (e) => {
      e.preventDefault();
      // form's input value
      let userSearch = this.state.query;
      this.props.handleSearch(userSearch);
    };