Scott
Scott

Reputation: 137

How to show form after onclick event React

I have a React component which returns a form with a button. When I click the button, I want another different form to show up on the same page. How do I do that? How do I return next form when I click the button? Below is just an example to give the main idea

function Example() {
  return (
    <div>
      <form>
        <button onclick={showForm}></button>
      </form>
    </div>
  )
}

Upvotes: 1

Views: 13999

Answers (2)

Fatemeh Qasemkhani
Fatemeh Qasemkhani

Reputation: 2042

Define an state to handle the visibility of your form.

import React, { useState } from 'react';

function Example() {
  const [showForm, setShowForm] = useState(false);

  const showForm = () => {
    setShowForm(!showForm);
  }

  return (
    <div>
      <form>
        <button onClick={showForm}></button>
      </form>

      {showForm && (
        <form>
          ...
        </form>
      )}
    </div>
  )
}

Upvotes: 14

yudhiesh
yudhiesh

Reputation: 6829

You could use tertiary operators. Here is a sample that you could use that changes from showing one component to another one.

Set state to be false initially then change it to true when the button is clicked this can be in your App.js then pass it down to the component that renders it.

const [ editing, setEditing ] = useState(false)

const editRow = user => {
        setEditing(true)

        setCurrentUser({ id: user.id, name: user.name, username: user.username })
    }

The button of the initial component should be like this

 <button onClick={() => setEditing(false)} className="button muted-button">
        Cancel
    </button>
<div/>

In your main App.js this is how you switch between the two components

<div>
    {editing ? : (render what component you want when it is set to true ) : (render the component you want when it is set to false)}

Upvotes: 0

Related Questions