Home > other >  JSX doesn't render on conditional render alongside with map function
JSX doesn't render on conditional render alongside with map function

Time:11-09

I want to render a component based on a variable being true or false. At the moment the condition comes up as true but the component isn't rendering at all.

Here is my code:

<div className={styles.container}>
   {array.map(item => {
    router.query.slug != item ? <Component /> : null;
    })}
</div>

My console is returning true for the condition router.query.slug != item so what am I missing?

Thanks

CodePudding user response:

You are missing to return the component from map function.

Here is the example that will match your problem:

Solution 1

<div className={styles.container}>
    {array.map(item => {
        return router.query.slug != item ? <Component /> : null;
    })}
</div>

Solution 2 with single line

<div className={styles.container}>
    {array.map(item => router.query.slug != item ? <Component /> : null)}
</div>

You can read about map function in here.

CodePudding user response:

If you use the block syntax, you need to specify the return keyword. Learn more about arrow-function

Try this way.

Example:

<div className={styles.container}>
   {array.map(item => {
     return (router.query.slug != item ? <Component /> : null)
    })}
</div>
  • Related