Home > Mobile >  <select> should have {defaultValue} or {value} instead of setting {selected}
<select> should have {defaultValue} or {value} instead of setting {selected}

Time:07-19

I'm building an E-Commerce site with reactjs with styled-component. My page product.jsx that has the <select> element with different sizes of product [XS,S,M,L,XL] that causes error always shows this error upon render in console.dev:

Warning: Use the defaultValue or value props on instead of setting selected on .

I tried this code right below before but it doesn't work as expected. I'm expecting to show the first element as disabled and shouldn't be selected at all:

<Filter>
  <FilterTitle>Size</FilterTitle>
    <FilterSize onChange={(e) => setSize(e.target.value)}>
        {product.size?.map((s) => (
              <FilterSizeOption key={s}>{s}</FilterSizeOption>
        ))}
  </FilterSize>
</Filter>

Please help me fix this code below not the above one.

product.jsx code:

const FilterSize = styled.select`
  margin-left: 10px;
  padding: 5px;
  cursor: pointer;
  outline: 0px;
  font-size: inherit;
`;
const FilterSizeOption = styled.option``;

//...

<Filter>
    <FilterTitle>Size</FilterTitle>
    <FilterSize onChange={(e) => setSize(e.target.value)}>
         <FilterSizeOption selected={true} disabled="disabled">
              Choose a size:
         </FilterSizeOption>
         {product?.product?.size.map((s) => (
              <FilterSizeOption key={s} value={s}>
                   {s}
              </FilterSizeOption>
         ))}
    </FilterSize>
</Filter>

CodePudding user response:

To resolve this error you need change value="default" instead of selected={true}, and on the FilterSize component should add defaultValue="default". The defaultValue and value with the same value, you will bind the default selection. The default value you can rename yourself.

Before

enter image description here

After

enter image description here

const FilterSize = styled.select`
  margin-left: 10px;
  padding: 5px;
  cursor: pointer;
  outline: 0px;
  font-size: inherit;
`;
const FilterSizeOption = styled.option``;

const sizes = ['XS', 'S', 'M', 'L', 'XL'];

function App() {
  const [size, setSize] = useState();

  return (
    <>
      <FilterSize defaultValue="default" onChange={e => setSize(e.target.value)}>
        <FilterSizeOption value="default" disabled="disabled">
          Choose a size:
        </FilterSizeOption>
        {sizes.map(s => (
          <FilterSizeOption key={s} value={s}>
            {s}
          </FilterSizeOption>
        ))}
      </FilterSize>
    </>
  );
}

export default App;
  • Related