I
I
ihoooly2018-08-21 16:31:49
React
ihoooly, 2018-08-21 16:31:49

How to replace one component with another on click in React?

Hello everyone, I have two different blocks:

<div className='first'>
  <div>
    <div>Login</div>
    <div><a href="#" className='reg'>or Register</a></div>
  </div>
  <div>
    <input type="text">
    <input type="text">
    <button>Войти</button>
  <div>
</div>

<div className='second'>
  <div>
    <div>Register</div>
    <div><a href="#" className='log'>or Login</a></div>
  </div>
  <div>
    <input type="text">
    <input type="text">
    <input type="text">
    <button>Зарегистрироваться</button>
  <div>
</div>

They will be located on the left side of the screen, by default the 'login' block should be shown, when you click on the 'or Register' link, the current block should be erased and another one displayed, and actually the opposite will happen further. If it were possible to use jquery, then by clicking on the link, one could simply add display: none to the block with the 'first' class, and give display: block to the second block. But now I looked and did not find this in the react.
How can you do this in react?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Proskurin, 2018-08-21
@ihoooly

Make them into separate components and conditionally render.
Rough, like this

A
Anton Spirin, 2018-08-21
@rockon404

I strongly recommend that before writing anything of your own, study the library and its capabilities better, since you do not know its basic concepts. Read about state management and conditional rendering, or rather the entire manual from cover to cover.

class Example extends Component {
  state = {
    activeForm: 'login',
  };
 
  setActiveForm = name => {
    this.setState({ activeForm: name });
  };

  render() {
    const Form = this.state.activeForm === 'login' ? Login : Registration;

    return (     
      <SideBar>
        <Form setActiveForm={setActiveForm} />
      </SideBar>
    );
  }
}

M
Mikhail Osher, 2018-08-21
@miraage

https://github.com/ReactTraining/react-router
https://github.com/reach/router

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question