how do I render a page in react using functional components when onSubmit?

Viewed 180
function Header() {
    const [search, setSearch] = useState('');
    const [{search_results}, dispatch] = useStateValue();

function to run when the form gets submit:

function search_item(event){
        event.preventDefault();
        if(search_results.length===0){
            alert("No results Found")
        }else{
            alert("Found Something");
            // render a search results page;            
        }
    }

I want to render a page like "/searchResults" after I hit enter which will contain my search_results state value.

    return (
        
        <div className="header">
            <img className="header__logo" src="" alt="" />
            <div className='header__searchBox'>
                <form onSubmit={search_item} className="header__search">
                    <input placeholder="Input The Keywords" onChange = {event => setSearch(event.target.value)}/>
                    <SearchIcon className="header__searchIcon"/>
                </form>
1 Answers

You have to declare a state(eg. result) initialized with null/undefined. call search_item and set the search result to that state. then use conditional rendering to render the results if it's there.

Assuming that you have a searchResult state that is set to the results, after you created a renderer function which gives a result item and returns a rendered component, it's how you can do conditional rendering for it:

<div>
  <form ...>
    ...
  </form>
  {searchResult && (
     <div>
       {searchResults.map(renderResultItem)}
     </div>
  )}
</div>
Related