skip to Main Content

Let’s say I have a React Select with a placeholder (‘Selected Value: ‘), and I want to keep the placeholder and append it into the selected value so that it looks something like (‘Selected Value: 1’). Is there any way to do it?

import Select from "react-select";

export default function App() {
  const options = [
    { value: 1, label: 1 },
    { value: 2, label: 2 },
    { value: 3, label: 3 },
    { value: 4, label: 4 }
  ];
  const placeholder = "Selected Value: ";
  return (
    <div className="App">
      <Select options={options} placeholder={placeholder} />
    </div>
  );
}

codesandbox: https://codesandbox.io/s/brave-chatterjee-pjol2d?file=/src/App.js:23-385

EDIT: Sorry, forget to mention, I do not want the placeholder to directly be in the labels of the options

3

Answers


  1. you can accept my answer

    import Select from "react-select";
    import { useState } from "react";
    
    export default function App() {
      const [selectBoxValue, setSelectBoxValue] = useState('')
      const options = [
        { value: 1, label: 1 },
        { value: 2, label: 2 },
        { value: 3, label: 3 },
        { value: 4, label: 4 }
      ];
      const placeholder = `Selected Value: ${selectBoxValue}`;
      return (
        <div className="App">
          <Select 
          options={options} 
          placeholder={placeholder} 
          value={placeholder}
          onChange={(event) => setSelectBoxValue(event.value)} />
        </div>
      );
    }
    
    Login or Signup to reply.
  2. just use these options:

    const options = [
        { value: 1, label: 'Selected Value: 1' },
        { value: 2, label: 'Selected Value: 2' },
        { value: 3, label: 'Selected Value: 3' },
        { value: 4, label: 'Selected Value: 4' }
      ];
    
    Login or Signup to reply.
  3. Read https://mui.com/material-ui/react-select/

    <Select
      value={personName}
      onChange={handleChange}
      renderValue={(selected) => {
      if (selected.length === 0) {
           return <em>Placeholder</em>;
      }
       return 'placeholder '+selected;
      }}
     >
    

    Possible two solutions:

    1. You can use renderValue to render what you want.
    2. You can use state and pass the value as value props. On handleChange you can change the state of value.
      it should work.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search