Next.js Discord

Discord Forum

How to select option in loop?

Answered
Japanese Bobtail posted this in #help-forum
Open in Discord
Japanese BobtailOP
Hi there. On page reload, the select field is selecting the right option. This works fine, but how do i fix the warning? "Use the defaultValue or value props on <select> instead of setting selected on <option>."

const items = [ { name: 'foo', link: '/foo' }, { name: 'bar', link: '/bar' }, ]; export default function Nav() { const router = useRouter(); const pathname = usePathname(); const origin = pathname.replace(/^\//, '').split('/')[0]; const handleChange = (e) => { router.push(e.target.value); }; return ( <select onChange={(e) => handleChange(e)}> {items?.map((item, index) => ( <React.Fragment key={index}> <option value={item.link} selected={origin == item.link.split('/')[1]} > {item.name} </option> </React.Fragment> ))} </select> ); }
Answered by B33fb0n3
What about doing it like this:
<select defaultValue={origin} onChange={(e) => handleChange(e)}>
        {items?.map((item, index) => (
            <React.Fragment key={index}>
                <option
                    value={item.link.split('/')[1]}
                >
                    {item.name}
                </option>
            </React.Fragment>
        ))}
    </select>
View full answer

8 Replies

@B33fb0n3 to remove the warning you need to set the defaultValue or value of the select to the selected value instead selected on the selected option
Japanese BobtailOP
If i change selected to defaultValue it doesnt work anymore.
you need to set it on the <select> not on the <option>
@B33fb0n3 you need to set it on the <select> not on the <option>
Japanese BobtailOP
for sure, but i cant get it. Because its known in the loop. That is why i am asking...
What about doing it like this:
<select defaultValue={origin} onChange={(e) => handleChange(e)}>
        {items?.map((item, index) => (
            <React.Fragment key={index}>
                <option
                    value={item.link.split('/')[1]}
                >
                    {item.name}
                </option>
            </React.Fragment>
        ))}
    </select>
Answer
@Japanese Bobtail Sir, thats so easy. Thanks. I solved my problem.
sure thing. Please mark solution