0

I have 3 components: Layout App Products

My Layout has this form:

                  <form className='d-flex'>
                    <input
                      name='search'
                      className='form-control mr-2 shadow-none'
                      type='search'
                      placeholder='Search'
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                    />
                    <button className='btn btn-outline-secondary' type='submit'>
                      <SearchIcon />
                    </button>
                  </form>

I passed search and setSearch through props.

In my App has this logic:

  const [search, setSearch] = useState('');
    <Layout search={search} setSearch={setSearch}>  
        <Route exact path='/' search={search} component={Products} />
    </Layout>

I pulled the search result from the Layout and created a state in the App and then trying to pass to the Products component.

In the product when I try to console the search result I see only an undefined result

1 Answer 1

1

Your method doesn't work because you are passing the search value into the Route component instead of the component it render. You can use the render property of the Route to pass any props you want to the routing component https://reactrouter.com/web/api/Route/route-render-methods

 const [search, setSearch] = useState('');
 <Layout search={search} setSearch={setSearch}>  
    <Route exact path='/'
       render={props=> <Products {...props} search={search} setSearch={setSearch}/>} />
 </Layout>

However, I suggest using a state management tool like redux if the application is big or create a context provider https://reactjs.org/docs/context.html#when-to-use-context.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.