Guru
Guru

Reputation: 17054

Reactjs not able to render a component which has a form

In my App.js, I have a class component Addition which will display 2 numbers and have a text box to get the result from the user. In the same file I have another class component App from which when I try to call <Addition/>, it renders the form perfectly as expected. However, I want the <Addition/> component to be triggered on a button click, which is not working.

class Addition extends Component{
render(){
   return (
  <form  onSubmit={this.validateResult}>
      <div >
         <Box1 val={this.state.value1}/>
         <Box1 val="+"/>
         <Box1 val={this.state.value2}/>
         <Box1 val="=" />
         <input className="resbox"
                value={this.state.result}
                onChange={event => this.setState({result: event.target.value})}
                required
          />
          <br/>
          <Box2  val={this.state.message} />
         <br/><br/>
         <input className="btn btn-info" type="submit" value="Submit" />
    </div>
  </form>
)
}
}

export default class App extends Component {
  handleClick= (event) => {
    event.preventDefault()
    console.log("inside handleclick")
    return (
      <Addition />
    );
  }

   render(){
  return (
  <div className="App">
    <header className="row App-header">
    <p >
     KIDS MATHS
     </p>
     <div  className="row col-2">
     <button className="btn btn-lg offset-1" onClick={this.handleClick}> + </button>
     </div>
    </header>
  </div>
   )
 }
}

When I tried to include the <Addition/> within the on-click event, the page simply remains same.

Please advice.

Upvotes: 1

Views: 35

Answers (1)

Auskennfuchs
Auskennfuchs

Reputation: 1737

Everything you want to render has to called directly from within the render function. You can use conditional rendering to achieve to selective rendering of Addition. For this add a state member and set the value accordingly at the trigger point. This will call render again and the content will be shown as expected.

export default class App extends Component {

  state = {
     showAddition: false
  }

  handleClick= (event) => {
    event.preventDefault()
    console.log("inside handleclick")
    this.setState({showAddition: true})
  }

   render(){
     const { showAddition } = this.state
     return (
       <div className="App">
         <header className="row App-header">
         <p >
          KIDS MATHS
         </p>
         <div  className="row col-2">
           <button className="btn btn-lg offset-1" onClick={this.handleClick}> + </button>
         </div>
       </header>
       {showAddition && <Addition/>}
     </div>
   )
 }
}

You can also consider to convert the components to function components and use useState instead of the state object. This will shorten the code a little bit.

Upvotes: 4

Related Questions