Jamie
Jamie

Reputation: 10886

Select component rendering

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?

Upvotes: 0

Views: 73

Answers (3)

Lakshya Thakur
Lakshya Thakur

Reputation: 8318

I think I can explain the initial load behaviour of your Select component.

When you are passing disabledOption as a prop, the default value of false is set to "Kies een land" now.

So when the following executes:-

  {disabledOption && (
    <option value="" disabled>
      {disabledOption}
    </option>
  )}

disabledOption being not an empty string is truthy and doesn't short circuit.

So the following element is rendered.

<option value="" disabled>
          {disabledOption}
        </option>

Since it is disabled, the first entry from countries is being shown which is NL.

Upvotes: 1

Prathap Reddy
Prathap Reddy

Reputation: 1739

Seems nothing wrong with your code (tested the exact code posted in question). Just check for any typos/try clearing browser cache/restarting node server.

Upvotes: 0

Allen Wong
Allen Wong

Reputation: 1433

Add selected props to the option that match the value

<option
  selected={val === opt.value}
  value={opt.value}
>
  {opt.label}
</option>

Upvotes: 1

Related Questions