I have been unable to create a split between an input field and a select field. What the algorithm does is when I put a number in input1, it generates the divisors of said number in the select. Now what I need is for it to divide what is in input1 with the value that I select in the select in another new input
. tried in several ways but I have not been able to achieve the division of these two fields the input one with the select
import { useState } from 'react'
export default function Pruebas() {
const [number, setNumber] = useState({input: 0, two: 0})
const [division, setDivision] = useState()
const [input, setInput] = useState()
const [values, setValues] = useState([])
const handleClick = event => {
event.preventDefault()
setValues([+input, ...values])
}
const useEffect1= ()=>{
const { input, two} = number
setDivision(Number(input) / Number(two))
}
const handleInput = (event) => {
const { name, value } = event.target
setNumber({...number, [name]: value})
}
return (
<div className="App">
<input placeholder='Ingrese divisor' value={input} onChange={event => setInput(event.target.value)} />
<button onClick={handleClick}>Agregar divisor</button>
<br /><br />
<select name='two' class='form-control'>
<option value='no' selected>
Select
</option>
{values.map((item, index) => (
<option key={index} value={item}>
{item - 1}
</option>
))}
</select>
<br />
<button onClick={useEffect1}>dividir</button>
<input value={division} placeholder="Resultado división" readOnly/>
</div>
);
}
It would be missing some changes to your code.
First, inside the function
useEffect1
, you're not fetching the data from the first input correctly. The data there was already exactly in the stateinput
.Afterwards, I wouldn't do the split within the
setDivision()
.Rather it would perform the split outside and the result would be what it would set.
The other change I would make would be the way to capture the select data.
You can add an event to it
onChange
and call the functionhandleInput
That way
<select>
we retrieve the data from and save it in the state.Making all those changes, all the code would look like this:
You can test it in SandBox and check if it does what you were looking for.
PS: I recommend that you choose a bit more intuitive names for your functions and objects. The names
useEffect1
andinput
are also very generic and do not describe the purpose for which they are used very well.