1

Is there a way to avoid the if and probably use a ternary or logical && for below scenario. Looks like react always looks for a an explicit return statement always for any component

const reactComp = ({ abc, xyz }) => {
if (something) {
    return (
       <Grid.Container>
        <Grid.Row>
          <Grid.Col md="6">
            <Panel title="Title">
               <Text>{mmmm}</Text>
            </Panel>
          </Grid.Col>
        </Grid.Row>
      </Grid.Container>
    );
  } else {
    return null;
  }
};

3 Answers 3

1

You can write a conditional statement directly within the return statement in the component. Here's an example of using a ternary operator. I have included something && something to make sure that something exists before running the conditional.

const ReactComp = ({ abc, xyz }) => {
    return (
     // Ternary operator within curly braces 
     // if something exists and if something
     { something && something ?
       // the return the following
       <>
       <Grid.Container>
        <Grid.Row>
          <Grid.Col md="6">
            <Panel title="Title">
               <Text>{mmmm}</Text>
            </Panel>
          </Grid.Col>
        </Grid.Row>
      </Grid.Container>
      </>
     // else
     : 
     // return the following
      <SomethingElse/> // or null 
     // close curly braces
     }
    );
};
Sign up to request clarification or add additional context in comments.

1 Comment

had to use the <> fragment just after the return to get this working. now i realise there are so many ways to do this :)
0

First of React components MUST to start with a big character, in this case ReactComp

If react believes it will not return anything, you could solve it by the following. It is also more clean.

if (!something) return null
 return (
       <Grid.Container>
        <Grid.Row>
          <Grid.Col md="6">
            <Panel title="Title">
               <Text>{mmmm}</Text>
            </Panel>
          </Grid.Col>
        </Grid.Row>
      </Grid.Container>
    );
  }

1 Comment

@user13021487 Cool! Consider marking the answer with the best solution as the answer by filling the grey "Mark as solution" button and upvoting the answers that helped out.
0

Yes, you can use the ternary operator to avoid multiple return statements as shown below:

const reactComp = ({ abc, xyz }) => (
  something ? (
    <Grid.Container>
      <Grid.Row>
        <Grid.Col md="6">
          <Panel title="Title">
            <Text>{mmmm}</Text>
          </Panel>
        </Grid.Col>
      </Grid.Row>
    </Grid.Container>
  ) : null
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.