Home > Software design >  Calling Props in JSX Invokes Invalid Syntax Error
Calling Props in JSX Invokes Invalid Syntax Error

Time:03-18

I'm creating a functional component that must render only if some variables are not empty. I want to incorporate the logic that determines whether the component renders or not directly within the component itself (to clean up the parent component).

The component render function exists as:

return(
    {
        props.var1 && props.var2 &&
        (<div ...
            </div>
        </div>)
    }
)

However, I get a syntax error pointing to the dot ('.') in props.var1 with message:

Unexpected token, expected "," 

If I remove props.var1 &&, I get the same error on props.var2.

Why is this happening and how can I circumvent it?

CodePudding user response:

To do conditional rendering based on a, well, condition, you should check for the condition and return null first:

// DeMorgan's laws (!(a && b) is the same as !a || !b)
if (!props.var1 || !props.var2) return null;

Then return the stuff you want to render as usual:

return (
    <div>...</div>
);

The error is occurring because the brackets ({}) make JS believe you are trying to return an object.

  • Related