0

I am having difficulties writing an if statement in React (bit new to this)

class TEST extends React.Component {
render() {
    const TEST = props => {
        if (props.isLoggedin("True")) {
            return (
                <Welcome />
            );
        }
        return (null);
    };
   }
 }
export default Switch(TEST);

The error message that I am getting is:

Your render method should have return statement

Not sure the best way to write this? Thanks

0

2 Answers 2

4

You don't need the const TEST = props => { } part, other than that looks okay.

Try as the following:

class TEST extends React.Component {
  render() {
    if (this.props.isLoggedin("True")) {
       return <Welcome />;
    }

    return null;
  }
}

export default Switch(TEST);

Or even shorter with ternary operator:

class TEST extends React.Component {
  render() {
    return this.props.isLoggedin("True") ? <Welcome /> : null;
  }
}

I hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but then it errors as Props is not defined - 'props' is not defined no-undef
@user3665791 Probably you need this.props instead.
1

Maybe you wanted to do something like this:

class TEST extends React.Component {
   render() {
      if (this.props.isLoggedin("True")) {
          return (
              <Welcome />
          );
      }
      return (null);
   }
 }

Or this (if you want to use functional components):

const TEST = props => {
    if (props.isLoggedin("True")) {
        return (
            <Welcome />
        );
    }
    return (null);
  };
}

You could also do it like this:

const TEST = props => props.isLoggedin("True") && <Welcome />

What you actually had is that you only defined a function inside your render method, that expected a return statement.

See: https://reactjs.org/docs/components-and-props.html#function-and-class-components

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.