Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to toggle between the login and signup forms in React when using an anchor tag is to use state to keep track of which form is currently displayed.

First, define state in the component's constructor or by using the useState hook:

constructor(props) {
  super(props);
  this.state = {
    showLogin: true
  };
}

or

const [showLogin, setShowLogin] = useState(true);

Then, use conditional rendering to display the appropriate form based on the state value.

render() {
  return (
    <div>
      {this.state.showLogin 
        ? <LoginForm /> 
        : <SignupForm />
      }
      <a onClick={() => this.setState({ showLogin: !this.state.showLogin })}>
        {this.state.showLogin ? 'Signup' : 'Login'}
      </a>
    </div>
  );
}

or

return (
  <div>
    {showLogin 
      ? <LoginForm /> 
      : <SignupForm />
    }
    <a onClick={() => setShowLogin(!showLogin)}>
      {showLogin ? 'Signup' : 'Login'}
    </a>
  </div>
);

When the anchor tag is clicked, it toggles the showLogin value and the form displayed on the page.