Nipun Garg Nipun Garg - 2 months ago 7
React JSX Question

How to change the form fields by clicking the button in REACT.js?

I have signup.jsx



import React from "react"
import { render } from "react-dom"

import SignupContainer from "./containers/SignupContainer"

class Signup extends React.Component {
user(){
this.props.type='user';
}
hotel(){
this.props.type='hotel';
}
render() {

return (
<div>
Registration Type :
<br></br>
<button onClick={this.user}>user</button>
<button onClick={this.hotel}>hotel</button>
<SignupContainer type={this.props.type}/>
<h1>Signup</h1>
</div>
);
}
}

render(<Signup type='user'/>, document.getElementById('Signup'))





My SignupContainer.jsx



import React from "react"

import Headline from "../components/Headline"

export default class SignupContainer extends React.Component {
render() {
if(this.props.type=='user'){
return (
<div className="container">
<div className="row">
<div className="col-sm-12">
<form action="/loginapp/" method="POST">


First Name:
<input type="text" name="first_name">
</input>

<br></br>
Last Name:
<input type="text" name="last_name"/>
<br></br>
Gender:
<input type="radio" name="gender" value="male" />Male
<input type="radio" name="gender" value="female" /> Female
<br></br>

<input type="submit" value="Submit"/>
</form>

</div>
</div>
</div>
);
} else if(this.props.type=='hotel'){
return(<h1>{this.props.type}</h1>);
}
}
}





What i want is that when i click on user button then it should show me the registration form and when i click on hotel button it should print hotel without reloading the page.

Answer

In React, props are passed down from parent to child, and should be considered immutable. On the other hand, state is used by components internally and can be updated with this.setState(), which triggers a re-render. Also, when using native JavaScript classes, you need to bind the class methods to the class if you want this to refer to class. So in your case, something like this should work:

class Signup extends React.Component {
      constructor(props) {
        super(props);
        this.state = { // this is your default state
          type: 'user'
        }
      }

      user() {
        this.setState({
          type: 'user'
        })
      }

      hotel() {
        this.setState({
          type: 'hotel'
        })
      }

      render() {
        return ( < div >
          Registration Type:
          < br > < /br>
            <button onClick={this.user.bind(this)}>user</button >
            <button onClick = {this.hotel.bind(this)}>hotel</button>
            <SignupContainer type={this.state.type} />
            <h1> Signup </h1>
            </div>
        );
      }
    }

    render( < Signup type = 'user' / > , document.getElementById('Signup'))

Comments