Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render results of search in another component in React?

I am a beginner in React and using Webpack to build into a bundle.js and display.

My need is to provide some search forms and accordingly display result below search form. So, for modularizing it, I have create a parent component containing both search and result view components.

Now that I have designed a form and written form onSubmit event handler, how should i proceed to render API results (dummy json for now) in the result component. I am attaching a brief pic of my intention for your reference.

enter image description here

like image 374
xploreraj Avatar asked Dec 18 '17 08:12

xploreraj


1 Answers

Here is my solution based on my comments above: https://codesandbox.io/s/q85oq0w10q

Create an HOC that will hold the state of your app, then your two children are merely used for rendering purpose and can be made pure functions

import React from 'react';
import { render } from 'react-dom';

const Result = ({results}) => {
  return results.map((r, i) => <div key={i}>{r}</div>);
}

const Search = (props) => {
  const {
    searchQuery,
    onChange,
    search
  } = props;

  return <div>
    <input
      type="text"
      value={searchQuery}
      onChange={onChange}
    />
    <button onClick={search}>Search</button>
  </div>;
}

class Container extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchQuery: '',
      results: []
    }

    this.onSearchQueryChange = this.onSearchQueryChange.bind(this);
    this.onSearch = this.onSearch.bind(this);
  }

  onSearchQueryChange(e) {
    this.setState({searchQuery: e.target.value});
  }

  onSearch() {
    // Simulate AJAX call
    setTimeout(() => {
      this.setState({results: [0, 1, 2, 3, 4]});
    }, 1000)
  }

  render() {
    const {results, searchQuery} = this.state;

    return <div>
      <Search
        searchQuery={searchQuery}
        onChange={this.onSearchQueryChange}
        search={this.onSearch}
      />
      <Result results={results} />
    </div>;
  }
}
like image 79
klugjo Avatar answered Oct 04 '22 21:10

klugjo