Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide a component in React using state

I'm trying to hide / show a component while checking a state value :

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Button from '@material-ui/core/Button'

class App extends Component {
    constructor(props) {
        super(props);
        this.state = true;
    }

    render() {    
        return (
          <div className="App">
            {this.state && <Button variant="raised" onClick={this.state=false}>Button</Button>}

          </div>
        );
    }
}

export default App;

I don't know where's the bug / wrong code, but the render doesn't seems to refresh.

like image 230
Zenyo Avatar asked Jan 19 '26 03:01

Zenyo


1 Answers

You are using it incorrectly. You have to init the state like this

constructor(props) {
  super(props);
  this.state = {show: true}
}

and render it like this

return (
    <div className="App">
        {this.state.show && <Button variant="raised" onClick={() => this.setState({show:false})}>Button</Button>}

      </div>
);
like image 189
Murat Karagöz Avatar answered Jan 20 '26 15:01

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!