I have a React ponent 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>
)
}
I have a React ponent 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>
)
}
Share
Improve this question
edited Jun 7, 2020 at 4:26
Fatemeh Qasemkhani
2,0422 gold badges18 silver badges26 bronze badges
asked Jun 7, 2020 at 4:01
ScottScott
1371 gold badge2 silver badges11 bronze badges
2
- Please describe more where you want to render form mean you want to toggel first form or create another div. – Arpit Vyas Commented Jun 7, 2020 at 4:05
- You should at least make an effort with some code. Lacking that, I'll simply say put the next form into a modal and have the onclick function set the modal visibility to true. Its easy! – jcklopp Commented Jun 7, 2020 at 5:31
2 Answers
Reset to default 14Define 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>
)
}
You could use tertiary operators. Here is a sample that you could use that changes from showing one ponent 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 ponent 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 ponent 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 ponents
<div>
{editing ? : (render what ponent you want when it is set to true ) : (render the ponent you want when it is set to false)}