'onChange is not working in react functional component while changing the value through state update
I am using mapbox in a project and here I am trying to get the latitude and longitude from the input box. I have set a value in input field and I want to change it while writing the but nothing is changing in the input box while trying to write something.
Please check the code
const [marker, setMarker] = useState({
latitude: 20.2961,
longitude: 85.8245
});
This is the rended input.
<div className='flex gap-6'>
<div className='relative w-1/2'>
<input onChange={(e) => setMarker({latitude:e.target.value, ...marker})} value={marker.latitude} type="number" placeholder='Latitude' className='py-4 w-full pl-12 text-xs rounded-md focus:outline-none border border-bottom-border' name="" id="" />
<MapPin className='absolute top-1/2 -translate-y-1/2 left-2 bg-[#0000000d] p-2 rounded text-gray-500' size={30} weight="bold" />
</div>
<div className='relative w-1/2'>
<input onChange={(e) => setMarker({longitude:e.target.value, ...marker})} value={marker.longitude} type="number" placeholder='Longitude' className='py-4 w-full pl-12 text-xs rounded-md focus:outline-none border border-bottom-border' name="" id="" />
<MapPin className='absolute top-1/2 -translate-y-1/2 left-2 bg-[#0000000d] p-2 rounded text-gray-500' size={30} weight="bold" />
</div>
</div>
Please help if you know the solution.
Solution 1:[1]
The spread operator should be used first here. Use something like this
onChange={(e) => setMarker({...marker, latitude:e.target.value })}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | halfer |
