Use of braces in react

#1

I’m trying to get a conditional statement working in braces. And neither of the following works. I can’t get the there isn't any data fragment working in the braces. If anybody has any videos and reading on this issue, then let me know.

const [tests, setTests] = useState();

const addAnotherTest = () => {
  if(tests) {
    tests.map(test => {
      return (<React.Fragment>{test._id}</React.Fragment>);
    })
  } else {
   return(<React.Fragment>there isn't any data</React.Fragment>); 
};

  return(

  // braces work on first statement and not on the second statement
  {tests ? tests.map(test => {
    return (<React.Fragment>{test._id}</React.Fragment>);
  }) :  return(<React.Fragment>there isn't any data</React.Fragment>);  
  }

  // function doesn't work at all
  {addAnotherTest()}

  );
};
#2

Ok, a cleaner way to write that:

const [tests, setTests] = useState([]);

then you test for

if(test[0])

your return function is … strange. If you have tests, you return, if you don’t you return so the section “{addAnotherTest()}” is never reached.

import React, { Fragment } from 'react'

return(
  {tests[0]
     ? <Fragment>
        {tests.map(test => {
            return <span>{test._id}</span>;
        })}
      </Fragment>
      : <Fragment>there isn't any data</Fragment>}

  // this function call looks like it is not supposed to be here
  {addAnotherTest()}

  );

The final/only return in a hook has to be DOM-able - things like JSX
You could have a look here: https://daveceddia.com/usestate-hook-examples/

#3

At first, it looks like you have too many returns.
I pasted this into a glitch pen and it immediately gave lint/compile errors which pointed to a misuse of braces and jsx.

The first fix is to explicitly enter JSX mode before opening the js braces by adding a new React.Fragment. I also needed to remove the return inside a return because that’s an obvious syntax error, as well as the extra semicolon halfway through an expression:

return(<React.Fragment>
  {tests ? tests.map(test => {
    return (<React.Fragment>{test._id}</React.Fragment>);
  }) : <React.Fragment>there isn't any data</React.Fragment>
  }

  // function doesn't work at all
  {addAnotherTest()}

  </React.Fragment>);

Also to demonstrate, if you remove the call toaddAnotherTest you can remove the opening braces altogether, because you are already in js mode at the start of the return statement:

return(
        tests ? tests.map(test => {
            return (<React.Fragment>{test._id}</React.Fragment>);
        }) : <React.Fragment>there isn't any data</React.Fragment>
    );
#4

as additional tip: use eslint with some good config (airbnb-config is good). and use prettier!