1

I have a react function. This function returns a search bar. When the search bar is changed a variable called esQueryDsl is set. I want to pass this variable back to the parent and also render the search bar.

Child:

export const SearchBar2 = (props) => {  
  const [query, setQuery] = useState(initialQuery);
  const [error, setError] = useState(null);

  const onChange = ({ query, error }) => {
    if (error) {
      console.log(error);
      setError(error);
    } else {
      console.log("query");
      setError(null);
      setQuery(query);
    }
    let esQueryDsl;
  
    try {
      esQueryDsl = EuiSearchBar.Query.toESQuery(query);
    } catch (e) {
      esQueryDsl = e.toString();
    }
  };

  const renderSearch = () => { 
    return (
      <EuiSearchBar
        defaultQuery={initialQuery}
        box={{
          placeholder: 'search'          
        }}
        onChange={onChange}
      />
    );
  };

  return (    
    <Fragment>
      <EuiFlexGroup alignItems="center">
        <EuiFlexItem>{renderSearch()}</EuiFlexItem>
      </EuiFlexGroup>
    </Fragment>
  );
};

Parent:

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      query: EuiSearchBar.Query.MATCH_ALL
    }        
    this.handleSearchFill = this.handleSearchFill.bind(this);
  }
  
  handleSearchFill = (data) =>{
    console.log('handleSearchFill')
    this.setState({query:data})
  }
  
  render() {
    return (
      <>
        <EuiPage> 
            <SearchBar2 onChange={this.handleSearchFill}/>  
        </EuiPage> 
      </>
    );}
}

When the search state is changed "query" gets logged to the console but "handleSearchFill" does not.

My intention is to pass the esQueryDsl back to the parent. Then pass it to a different child to render the results.

I was trying to refer to this question.

spyderman4g63
  • 4,087
  • 4
  • 22
  • 31

1 Answers1

0

Instead of defining a new state variable in the child. Use the state of the parent and pass a function that manipulates this state to the child. Now, whenever the query changes in the child, use the function passed as props to change the parent state. This is called lifting up the state.

From the code, I see that you've already done that

Changes:

Add this line in the try block in your onChange function

props.onChange(esQueryDsl);

Also, I don't think, the state query is useful in the child component.


  1. To use this state in another child of the same parent, just pass this state (query) as a prop to that child.

Ex:

// In parent     
return (
        <EuiPage> 
            <SearchBar2 onChange={this.handleSearchFill}/>  
            <SecondChild query={this.state.query}/>
        </EuiPage> 
);
Gowtham
  • 152
  • 10