0

Is there a way to achieve conditionally rendered content below but instead of using {renderAuthButton()} in the return statement, I want to achieve running renderAuthButton() with onCLick instead?

class App extends Component {
  // ...

  render() {
    let {isLoggedIn} = this.state;

    const renderAuthButton = () => {
      if (isLoggedIn) {
        return <button>Logout</button>;
      } else {
        return <button>Login</button>;
      }
    }

    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {renderAuthButton()}
      </div>
    );
  }
}

2 Answers 2

3

I don't really understand your need but to render conditionally, you can do something like that

state = {
  show: false,
}
<div className="App">
        <button onClick={() => this.setState((prev) => { show: !prev.show })}>Toggle</button>
        {this.state.show && <MyComponent />}
      </div>
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the confusion! I want to have a button that when clicked achieves the filtering action...i.e when clicked only show data that has a condition and when clicked again shows all data ...something like that
1

I'm not completely sure what you're trying to do but this is how you would conditionally render content in react:

class App extends React.Component {
  constructor(props){
    super(props);
    
    this.state = {
      show: false
    }
    
    this.toggleShow = this.toggleShow.bind(this);
  }
  
  toggleShow(){
    this.setState({show: ! this.state.show})
  }
 
  render(){
    return (
      <div>
        <button onClick={this.toggleShow}>Filter Content</button>
        
        {this.state.show ? (
          <p>This content is conditionally shown</p>
        ) : (
          <p>The content is now hidden</p>
        )}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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.