简体   繁体   中英

select default value is not working reactjs

im triying to select by default a value into a select input but the input is not recognizing that value until i change it manually. By the default i set "All" as my default value. here is my code and the codesandbox link:

import "./styles.css";
import React, { useState, useEffect } from "react";
import { FormField } from "react-form-input-fields";
import "react-form-input-fields/dist/index.css";

export default function App() {
  let [type, setType] = useState("All");
  const types = [
    { label: "All", value: "All" },
    { label: "Afganistan", value: "Afganistan" },
    { label: "Albania", value: "Albania" },
    { label: "Algeria", value: "Algeria" },
    { label: "American Samoa", value: "American Samoa" },
    { label: "Andorra", value: "Andorra" },
    { label: "Angola", value: "Angola" }
  ];

  function handletype(e) {
    setType(e);
  }

  return (
    <div className="App">
      {/* <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2> */}
      <FormField
        type="select"
        value={type}
        option={types}
        label={"Select your type"}
        keys={"label"}
        handleOnChange={(value) => handletype(value)}
      />
    </div>
  );
}

link:

https://codesandbox.io/s/select-problem-ykplcm

The library you use has a bug

The source code reveals that the value prop is only checked in componendDidUpdate , but this hooks is not called for the initial render

I would rather use a different library

One easy fix is that set label= [hook value]

import "./styles.css";
import React, { useState, useEffect } from "react";
import { FormField } from "react-form-input-fields";
import "react-form-input-fields/dist/index.css";

export default function App() {
  let [type, setType] = useState("All");

  return (
    <div className="App">
      {/* <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2> */}
      <FormField
        type="select"
        value={type}
        option={types}
        label={"Select your type"}
        keys={"label"}
        handleOnChange={(value) => handletype(value)}
      />
    </div>
  );
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM