How to render results of search in another component in React?
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>;
}
}
I believe this is what you are looking for. Worked example fiddle
So the idea is to keep your result in Container
component and pass it down to Result
component. Also Container
component should pass a callback function to your Search
component and it will be triggered with a API result from the Search
component.
Also you may want to take a look at Redux
. This is a library for managing your app state. With Redux
it can be achieved in more easiest way.
Hope it will help you.