How to return empty jsx if condition is false using react?

Viewed 301

i want to render nothing if the condition fails using react.

below is my code,

function Parent () {
    const iconRef = React.createRef();
    const iconRect = iconRef && iconRef.getBoundingClientRect();
    return( 
        <button ref={iconRef}/>
        <Child iconRect={iconRect}/>
    );
}


function Child({iconRect}: Props) {
    return (
        {iconRect ? (
            <div class="wrapper">
                <div class="dialog">
                    //something
                </div>
            </div>
         ) : null}
     );
 }

But this doesnt work . it gives error Syntax error unexpected token ,

could someone help me with this. thanks.

3 Answers

The parent component needs a React.Fragment.

https://reactjs.org/docs/fragments.html

function Parent () {
    const iconRef = React.createRef();
    const iconRect = iconRef && iconRef.getBoundingClientRect();
    return( 
        <React.Fragment>
            <button ref={iconRef}/>
            <Child iconRect={iconRect}/>
        </React.Fragment>
    );
}

You can just return null to render nothing.

Your code doesn't works because there are couple of problems in your code:

  • Parent component is returning two adjacent elements which is incorrect. You cannot have two adjacent React components next to each other without a common parent element.

    You need to wrap the JSX code returned from the Parent component in a wrapper element.

    return (
       <div>
         <button ref={iconRef}/>
         <Child iconRect={iconRect}/>
       </div>
    );
    

    If you don't want to render an extra element, you can use React.Fragment component as a wrapper element.

    return (
       <>
         <button ref={iconRef}/>
         <Child iconRect={iconRect}/>
       </>
    );
    
  • Curly brackets around the ternary expression, in the Child component, are not needed. You only need the curly brackets to wrap the javascript code written between JSX code.

    return (
      iconRect ? (
          <div class="wrapper">
              <div class="dialog">
                  {/* something */}
              </div>
          </div>
       ) : null
    );
    

Remove the unwanted curly braces and it would work as expected, thats the reason for the error

function Child({iconRect}: Props) {
    return (
        iconRect ? (
            <div class="wrapper">
                <div class="dialog">
                    //something
                </div>
            </div>
         ) : null
     );
 }
Related