spring_hiber
spring_hiber

Reputation: 135

How to hide a Button using React

I'm new to React and I would like to hide a button after the click. Below the two code segments below are the proptypes. Do I need to have a hideSubmit Button? How do I hide the button after click? I read that I can do it by state or css. Since this is a button it seems it would be easier to use css? Any help would be appreciated.

Upvotes: 1

Views: 17618

Answers (2)

arvind grey
arvind grey

Reputation: 160

    /* eslint-disable jsx-a11y/img-has-alt,class-methods-use-this */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import todoStyle from 'src/style/todo-style.scss';
import { Router, Route, hashHistory as history } from 'react-router';
import Myaccount from 'src/components/myaccount.jsx';

export default class Headermenu extends Component {

  constructor(){
  super();

  // Initial state
  this.state = { open: false };

}

toggle() {
  this.setState({
    open: !this.state.open
  });
}

  componentdidMount() {
    this.menuclickevent = this.menuclickevent.bind(this);
    this.collapse = this.collapse.bind(this);
    this.myaccount = this.myaccount.bind(this);
    this.logout = this.logout.bind(this);
  }

  render() {
    return (
      <div>

        <div style={{ textAlign: 'center', marginTop: '10px' }} id="menudiv" onBlur={this.collapse}>
          <button onClick={this.toggle.bind(this)} > Menu </button>

          <div id="demo" className={"collapse" + (this.state.open ? ' in' : '')}>
            <label className="menu_items" onClick={this.myaccount}>MyAccount</label>
            <div onClick={this.logout}>
              Logout
            </div>
          </div>

        </div>
      </div>
    );
  }

  menuclickevent() {
    const listmenu = document.getElementById('listmenu');
    listmenu.style.display = 'block';
  }



  logout() {
    console.log('Logout');
  }
  myaccount() {
    history.push('/myaccount');
    window.location.reload();

  }


}

enter code here

Upvotes: -1

Patrick
Patrick

Reputation: 3367

please see this fiddle on how to conditionally hide an element :

https://jsfiddle.net/69z2wepo/77987/

Base concept is that in your render you do this ;

  render: function() {
    return (<div>
    {this.state.clicked && <div>Shown or hidden?</div>}
    </div>);
  }

The idea is that you depend on the Component state to decide if anything should be rendered. you manipulate the state which forces a re-render for the component.

I think this is a "better" way than using css, but css has it's uses as well.(this can be used to conditionally add a 'hidden' class to the element)

Upvotes: 5

Related Questions