Home > Blockchain >  How to render a component conditionally?
How to render a component conditionally?

Time:12-26

I have shop.js component where Navbar and ProductList Components are render.I want when someone search then instead of ProductList Component ,searchShop component should render.

Shop Component

const Shop = () => {
    return (
        <div className='bb1'>
            <Navbar/>
            <ProductList/>
            <Footer/>
        </div>
    );
};

export default Shop;

Navbar Component

const Navbar = () => {
 const [state,setState]=useState({
        searchText:'',
    })

   
//Some API CALL run only when user search something
return(

 state.searchText?<SearchShop/>:""

)}

CodePudding user response:

But you need to clarify if you need component inside the Navbar, or instead of the ProductList component. If you want the ProductList to be replaced, you need to propagate the API call via some kind of state management, and have your logic in the Shop function:

const Shop = () => {
searchText = getStateFunction(state => state.searchText)

return (
    <div className='bb1'>
        <Navbar/>
      {searchText ? <ProductList/> : <SearchShop/>}
        <Footer/>
    </div>
   );
};

export default Shop;

There are many options for global state, I suggest you go look through the different options, but my absolute favorite to recommend, is Zustand. It's very easy to both setup, and use.

According to the React documentation you can do conditional rendering in several ways. Inline, etc., make sure you are using the the method you are most familiar or comfortable with.

CodePudding user response:

Add a function in shop.js where you need to set the visibility of product list and pass the function reference to navbar. So when search text is updated call the function.

    const Shop = () => {
        const [showProduct, setShowProduct] = useState(true);
        const change_product_display_handler = (state) =>{
            setShowProduct(state)
    }
    return (
        <div className='bb1'>
            <Navbar setProduct={change_product_display_handler}/>
            {showProduct &&<ProductList/>}
            <Footer/>
        </div>
    );
};

export default Shop;

In navbar in function where you got values of search text add the following function

const Navbar = () => {
 const [state,setState]=useState({
        searchText:'',
    })
const on_search_handler = () =>{
var searchvalue = //get value here;
//update setstate
 if (searchvalue === '') {
        props.setProduct(true);
    } else {
props.setProduct(false);
}
return(  );
};

export default Navbar ;
  • Related