0

I am trying to show the 'edit-btn' only if the user is logged in. What is the best way to achieve this in ReactJS? By rendering the component without the element if not logged in and rendering the element if the user is logged in? If so, what is the best approach to achieve this? I am quite new to ReactJS.

class LeftBlock extends React.Component {

  render() {
    return (
      <div className="left-block">
        {this.props.children}
        <a href="#" className="edit-btn"><i className="fa fa-pencil"></i></a>
        <br className="clear" />
      </div>
    );
  }

}

1 Answer 1

2

You can conditionally render components, even if they are null.

class LeftBlock extends React.Component {

    render() {

        var isAuth = false; // You'll need to figure out a way how to get this - From a store maybe or cookie?
        var button;
        if (isAuth){
            button = (<a href="#" className="edit-btn"><i className="fa fa-pencil"></i></a>);
        }

        return (
            <div className="left-block">
            {this.props.children}
            {button}
            <br className="clear" />
          </div>
        );
    }
}

So in this case, if isAuth is false, nothing will be rendered in place of {button}.

In terms of getting the isAuth status, I'd recommend having an AuthenticationStore which you can then get authentication information from within your components.

Checkout the Flux architecture if you're not already familiar with it. https://facebook.github.io/flux/docs/overview.html

Update

Fiddle: https://jsfiddle.net/6yq1ctcp/1/

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

2 Comments

Thanks Tom, for some reason I am getting a syntax error at: Module build failed: SyntaxError: Unexpected token (37:6) 35 | class LeftBlock extends React.Component { 36 | > 37 | var isAuth = false; Any idea whats wrong?
Thanks, I had a mistake in my code, sorry for the trouble.

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.