Gaurav Soni Gaurav Soni - 17 days ago 5
Javascript Question

Rendering new component on click in react

I'm practicing react and trying to render a new component on click of a button. Here the first page is email and the component i want to render contains password page.



class App extends React.Component {
passwordpage(){
return(
<form>
<div className="mainapp">
<h2> Password</h2>
<input type='Password' className="inputpassword" placeholder='Enter Password' required/>
<div>
<button type="submit" className="loginbutton">Next</button>
</div>
</div>
</form>
);
};

render() {
return (
<form>
<div className="mainapp">
<h2>Email Id</h2>
<input type='email' ref='enteremail'className="inputemail" placeholder='Enter Username' required/>
<div>
<button type="submit" onClick={this.props.passwordpage} className="loginbutton">Next</button>
</div>
</div>
</form>

);
}
}

ReactDOM.render(<App/>,document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>




Answer

The simplest is to have the password page already prepared in your render(), and to show/hide it depending on the component state, that is mutated by the onClick handler, something along those lines:

showPasswordPage() {
  this.setState({showPassword: true });
}

render() {
  const passwordPage = (<form>
    <div className="mainapp">
      <h2> Password</h2>
      <input type='Password' className="inputpassword" placeholder='Enter Password' required/>
      <div>
        <button type="submit" className="loginbutton">Next</button>
      </div>
    </div>
  </form>);

  const mainForm = (<form>
    <div className="mainapp">
      <h2>Email  Id</h2>
      <input type='email' ref='enteremail'className="inputemail" placeholder='Enter Username' required/>
      <div>
        <button type="submit" onClick={this.showPasswordPage} className="loginbutton">Next</button>
      </div>
    </div>
  </form>);

  return { this.state.showPassword ? passwordPage : mainForm };