Home > Net >  React Select does not change Label according to defaultValue
React Select does not change Label according to defaultValue

Time:05-29

import React from "react";
import { useState } from "react";
import Select from "react-select";

const EditMitarbeiter = () => {
    const optionsField1 = [
        { id: "1", value: "test1", label: "Test1"},
        { id: "2", value: "test2", label: "Test2"},
        { id: "3", value: "test3", label: "Test3"},
        { id: "4", value: "test4", label: "Test4"},
    ];
    
    const[functions, setFunctions] = useState([
        {field1:"test1",field2:"test2",field3:"test3",input:"Test"}
    ]);

    const handleFunctionAdd = () => {
        setFunctions([...functions, {field1:"",field2:"",field3:"",input:""}]);
    };

    const handleFunctionRemove = (event, index) => {
        event.preventDefault(); // verhindert Default Verhalten von Button, ist somit kein "Submit-Button" mehr und lädt Seite nicht neu
        console.log(index); // FEHLER: este Funktion wird nicht entfernt, sondern folgende
        const list = [...functions];
        list.splice(index,1);
        setFunctions(list);
    };

    const handleFunction1Change = (event, index) => {
        const newFunctions = [...functions];
        newFunctions[index].field1 = event.value;
        setFunctions(newFunctions);
    }

    return (
        <div>
            <div id="content">
                <form id="Funktion">
                    <legend>Funktionen</legend>
                        {functions.map((f,index) => (
                            <div key={index} id="function-box">
                                <div ><Select options={optionsField1} defaultValue={f.field1} onChange={(event) => handleFunction1Change(event,index)}/></div>
                            </div>
                        ))}
                </form>
            </div>
        </div>
    );
}

export default EditMitarbeiter;

I got the problem that my the label of the ReactSelect does not change and it stays blank. I already looked through some similar questions but i couldn't figure out why my example does not work even though i used the solutions of the other questions.

Also a side question, is it worth to use ReactSelect over the normal HTMLSelect cuz i just get problems with the ReactSelect...

CodePudding user response:

f.field1 = "test1" That presenting in default value

defaultValue="test1"

but default value must be like this

defaultValue={{label:"xyz",value:"xyz"}}

Fou You , this will work

 defaultValue={optionsField1.find((d) => d.value === f.field1)}

CodePudding user response:

I have run your code in codesandbox. There I see no issue selecting any option. Here is the link: https://codesandbox.io/s/react-app-c08zs4?file=/src/App.js

If you meant anything else, please let me know.

  • Related