Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I keep and append placeholder text into the selected value in React Select?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading