Home > Mobile >  select default value is not working reactjs
select default value is not working reactjs

Time:12-26

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

CodePudding user response:

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

CodePudding user response:

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

  • Related