Home > Back-end >  How can I get default value of antd select?
How can I get default value of antd select?

Time:10-21

I have a simple antd select which has three options ( "Jack", "Lucy" and "Laura"). Lucy is default value. I have h2 that displays value of select when I change any value. When I click "Jack", it displays: "Field value is Jack" and same happens for other two values as well. I am using onChange event to catch the value and then store it in a state and then display it. Problem is I want to display "Field value is lucy" when page loads and I am not able to achieve this. When I change value to other than lucy and again come back to lucy then onChange event captures the value of lucy in state and it gets displayed, but I want to display its value from start, when page loads without changing value other than lucy. How can I extract default value of this antd select?

Here is code: https://stackblitz.com/edit/react-ey3kfq?file=src/App.js,src/style.css

Help would be greatly appreciated.

CodePudding user response:

Creds for providing a working sample showing the issue. Here's a fixed solution: https://stackblitz.com/edit/react-fekvet?file=src/App.js

The issue is because your Select control had a defaultValue which didn't align with what was being displayed. The easy fix is to provide useState with your intended initial value, and use that as the value for defaultValue

CodePudding user response:

You can put default value in your useState to show the default value. Like the below code snippet. Hope this will help you.


const DEFAULT_VALUE = 'lucy'

export default function App() {
  ....
  const [fieldValue, setFieldValue] = useState(DEFAULT_VALUE);
  ...
  return (
      ...
      <Select
        defaultValue={DEFAULT_VALUE}
        ....
      >
        ...
      </Select>
      ....
  );
}
  • Related