Randy_Johnson's avatar

ReactJS Select Funky Happenings

Hi, I am confused to what is happening with the setState function. Clicking an element inside the select box will produce the previous value of the selected. Example: { 0, 1, 2, 3} selecting the the second element shows a zero, thirds element shows a one, and so on.

Clearly this cannot be normal and I am doing something wrong.

import { forwardRef, useEffect, useRef, useState } from 'react';

export default forwardRef(function SelectBox(
    { type = 'text', name, id, value, className, autoComplete, required, isFocused, handleChange, objects },
    ref
) {
    const input = ref ? ref : useRef();

    const [selected, setSelected] = useState(0);

    useEffect(() => {
        if (isFocused) {
            input.current.focus();
        }
    }, []);

    function handleChange(e) {
        setSelected(e.target.value)
        console.log(selected)
    }

    return (
        <div className="flex flex-col items-start">
            <select
                type={type}
                name={name}
                id={id}
                value={value}
                className={
                    `border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm ` +
                    className
                }
                ref={input}
                autoComplete={autoComplete}
                required={required}
                onChange={(e) => handleChange(e)}
            >
                <option key="0" value="0" defaultValue>Open this select men</option>
                {objects.map((element) => (
                    <option key={element.id} value={element.id}>{element.name}</option>
                ))}
            </select>
        </div>
    );
});

0 likes
1 reply
Randy_Johnson's avatar
Randy_Johnson
OP
Best Answer
Level 8

I fixed it by accident.

On the parent of the component for anyone that is interested. What a head ache.

    const onHandleChange = (event) => {
        // setData(event.target.name, event.target.type === 'checkbox' ? event.target.checked : event.target.value);

        console.log(event.target.value);
    };


<TextInput 
                        type="text" 
                        name="name" 
                        id="name" 
                        className="w-full py-3 shadow" 
                        handleChange={onHandleChange}
                    />

Please or to participate in this conversation.