Select component rendering Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Select component rendering without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’ve made a custom select component in react it looks like this:

import { useDispatch, useSelector } from "react-redux";

const Select = ({
  id,
  options,
  dispatchKey,
  selector,
  disabledOption = false,
}) => {
  const dispatch = useDispatch();
  const formValue = useSelector((state) => state.form[selector]);

  return (
    <select
      id={id}
      required
      onChange={(e) => dispatch({ type: dispatchKey, value: e.target.value })}
      value={'IT'}
      className="mt-1 block form-select w-full py-2 px-3 py-0 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:shadow-outline-blue focus:border-blue-300 transition duration-150 ease-in-out sm:text-sm sm:leading-5"
    >
      {disabledOption && (
        <option value="" disabled>
          {disabledOption}
        </option>
      )}
      {options &&
        options.map((o) => (
          <option value={o.value} key={o.value}>
            {o.text}
          </option>
        ))}
    </select>
  );
};

export default Select;

I use it like this:

const countries = [
    { value: "NL", text: "Nederland ๐Ÿ‡ณ๐Ÿ‡ฑ" },
    { value: "BE", text: "Belgie ๐Ÿ‡ง๐Ÿ‡ช" },
    { value: "DE", text: "Duitsland ๐Ÿ‡ฉ๐Ÿ‡ช" },
    { value: "IT", text: "Italiรซ ๐Ÿ‡ฎ๐Ÿ‡น" },
  ];

<Select
  id="country"
  options={countries}
  dispatchKey="SET_COUNTRY"
  selector="country"
  disabledOption="Kies een land"
/>

This dropdown shows countries. Right now I’ve hardcoded ‘IT’. However when the component is loaded it shows ‘NL’ when I type something in another field it suddenly displays ‘IT’.

What am I doing wrong, why is ‘IT’ not displayed instantly?

Answer

Add selected props to the option that match the value

<option
  selected={val === opt.value}
  value={opt.value}
>
  {opt.label}
</option>
We are here to answer your question about Select component rendering - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji