简体   繁体   中英

How to insert title inside react-select above selected option?

I want to add static title to react-select that will appear above my current selected options.

在此处输入图片说明

How it can be done with react-select ?

thank you :)

I think you are looking for InputLabel (Material-UI equivalent).

In react-select there is an option to add label with placeholder prop. It only shows on top, when you have selected something from dropdown, but I think it is a good start.

Have a look at the example: https://codesandbox.io/s/6x9405rlqk

Placeholder Component to be displayed in the input when nothing is selected. By default it is the text 'Select...' See props docs for more details: https://react-select.com/props#select-props

It looks like a floating label is what you're looking for. A "placeholder" is meant to disappear when an actual input is entered so trying to make the placeholder work as a label would be counter-intuitive.

在此处输入图片说明

You can add a floating label to react-select by adding a label to a custom control component:

// CustomControl.tsx

import React from "react";
import styled from "styled-components";
import { components } from "react-select";

export const Control = (props: any) => {
  return (
    <>
      <Label isFloating={props.isFocused || props.hasValue}>Select</Label>
      <components.Control {...props} />
    </>
  );
};

const Label = styled.label<{ isFloating?: boolean }>`
  left: 10px;
  pointer-events: none;
  position: absolute;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;

  top: ${(props) => (props.isFloating ? `5px` : `35%`)};
  font-size: ${(props) => (props.isFloating ? `0.5rem` : `1rem`)};
`;

Then just add this custom control component to Select:

<Select 
  ...
  components={{ Control }} 
  placeholder=""
/>

Live demo | GitHub Issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM