user9117353
user9117353

Reputation:

how to make a button appear disappear on click of another button?

I am facing problem with toggling of appearance of button in my react project.

I am working on a mini react project. I want my show button to toggle appearance of another button valued "submit" using react/JSX and not using CSS.

import React, { Component } from 'react';
var show;
class FormComp extends Component {

  constructor(props) {
    super(props);
    this.state = {
      show : Boolean()
    }
    this.handleshow = this.handleshow.bind(this);
  }

  handleshow() {
    this.setState ((prevState) => {
      return {
        show : !prevState.show
      }
    });
  }

  render() {
    <form onSubmit={this.handlesubmit}>
      <input type="submit" value="Show" onClick = {this.handleshow}/>

      { this.state.show ? <button>Submit</button> : null }
    </form> 
    </div>
  );
}}

export default FormComp;

Is there any problem with my conditional rendering statement?

Upvotes: 2

Views: 5713

Answers (2)

Juorder Gonzalez
Juorder Gonzalez

Reputation: 1652

Your conditional rendering is good, the problem comes when you are updating your show state , so in your handleShow function make a little change

handleshow() {
this.setState ((prevState) => {
  return {
  show : !prevState.show
}});}

Plus, change the type submit of show button to type button. That will do the trick.

Upvotes: 3

iambinodstha
iambinodstha

Reputation: 1007

this might help you. read the comment in the code to understand more. and on the other hand you don't need to declare variable and it's data type to use it.

import React, { Component } from 'react';

class FormComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show : false
    }
    this.handleshow = this.handleshow.bind(this);
  }

  handleshow() {
    // toggle your show state
    // for example if your show state is false than it will be true and if true than it will be false
    //exclamation mark(!) will work as not operator
    this.setState({show: !this.state.show);
  }

  render() {
    return(
      <div>
       <form onSubmit={this.handlesubmit}>
        <input type="submit" value="Show" onClick = {this.handleshow}/>
        // when your show state is true submit button will show up otherwise it will not shown up
        { this.state.show ? <button>Submit</button> : null }
       </form> 
    </div>
    )
  );
}}

export default FormComp;

Upvotes: 1

Related Questions