Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling Props in JSX Invokes Invalid Syntax Error

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading