good day, I have two buttons, one is called "yes" and the other button is called "no", when I click on the "yes" button it opens a div with an "input" type text and the same thing when I click on it in the "no" button, what I need is that the information that I write in the input is maintained, since if I write something in one of the inputs and activate the div "yes" or the div "no" what I have written in the input is cleared:
code: https://codesandbox.io/s/hopeful-voice-di2frw?file=/src/App.js
code:
import React,{useState} from 'react'
function Pruebas3() {
const [value2, setValue2] = useState("");
const handlerOnClick = (e) => {
// console.log(e.target.value) // si || no
setValue2(e.target.value)
}
return (
<div>
<div className="col-sm-6">
<div className="form-check">
<input
type="button"
name="boton1"
value="no"
onClick={handlerOnClick}
/>
<input
type="button"
name="boton1"
value="si"
onClick={handlerOnClick}
/>
</div>
</div>
<div className="col-sm-7">
{value2 === "si" && (
<div className="card">
<div className="card-body">
<h1>DIV si</h1>
<input type="text" name="div1" />
</div>
</div>
)}
</div>
<div className="col-sm-7">
{value2 === "no" && (
<div className="card">
<div className="card-body">
<h1>DIV no</h1>
<input type="text" name="div2" />
</div>
</div>
)}
</div>
</div>
)
}
export default Pruebas3
What happens is that you have two
inputs
of typebutton
that when you press them it opens the<div>
and the<input>
with typetext
. But you are not saving in the state the value of those inputs of type text.You have two options:
You can create a state with
useState
for each input of type text and every time the input is updated, its state is updated.Or you can create a state
useState
that saves the text of the two inputs and depending on which one is thename
input that is updated, we apply the state update to that one.The function that will be in charge of updating that state:
This way we can set the inputs as
If you see each
input
has a propertyname
that identifies the input. We use that prop inhandleInputValue
to assign thekey
with thevalue
=>[e.target.name]: e.target.value
which translates to[si]: e.target.value
or[no]: e.target.value
in the case ofno
and updates each key with its respective value.You can see the sandbox .