DEV Community

Cover image for React-select's formatOptionLabel
graceIsAnEngineer
graceIsAnEngineer

Posted on

React-select's formatOptionLabel

Today is officially 90 days that I’ve been a junior software engineer and I thought I would clarify or further explain a feature that I learned about today React-selects prop: formatOptionLabel.

Let me start from the top, React-select is a select control for React that you can import within any app like so:
import Select from ‘react-select’;

After you import the select component from react-select then you’re good to use it, like for example if you wanted just a select drop down you could do this:

import Select from "react-select";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Select />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Code sandbox example below:
https://codesandbox.io/s/compassionate-montalcini-0hfzz0?file=/src/App.js:23-195

formatOptionLabel is a prop that you pass to the select component to format the option labels in the menu as well as format the value that displays. The parameters that you will pass in to formatOptionLabel will be the option and context. Context can either be menu which means the drop down options or it can be value which is that value displayed in the select field.

import React from "react";
import Select from "react-select";

const myOptions = [
  { value: "1", label: "One", emotion: ":D" },
  { value: "2", label: "Two", emotion: "D:" },
  { value: "3", label: "Three", emotion: ":)" }
];

export default function App() {
  return (
    <div>
      <h1>Let's do this</h1>
      <Select
        options={myOptions}
        formatOptionLabel={(option, { context }) => {
          return context === "menu" ? option.label : option.value;
        }}
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here’s a Code sandbox example below:
https://codesandbox.io/s/magical-euler-ezwwwn?file=/src/App.js

Based on the context we can make it so that the dropdown values and what is displayed is different! I was having trouble finding different examples of formatOptionLabel so I hope this helps someone!

Top comments (0)