Skip to content

Commit 531b08b

Browse files
authored
docs(Input): add controlled Input example (#8280)
1 parent a905391 commit 531b08b

2 files changed

Lines changed: 43 additions & 2 deletions

File tree

packages/main/src/webComponents/Input/Input.mdx

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,30 @@ import { excludePropsForAbstract } from '@sb/utils';
2222

2323
<br />
2424

25-
# More Examples
25+
## More Examples
2626

2727
<br />
2828

29-
## Input with customizable SuggestionItem
29+
### Fully Controlled Input
30+
31+
Different from the native `input` element, the `Input` (`ui5-input`) web component is uncontrolled even if the `value` prop is provided (see [React docs](https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable)).
32+
To make it fully controlled, call `event.preventDefault()` in the `onInput` handler.
33+
34+
In the example below, only letters are allowed to be entered into the `Input` component.
35+
36+
<Canvas of={ComponentStories.FullyControlled} />
37+
38+
```ts
39+
const handleInput: InputPropTypes['onInput'] = (event) => {
40+
event.preventDefault();
41+
const { value } = event.target;
42+
if (/^[a-zA-Z]*$/.test(value)) {
43+
setValue(value);
44+
}
45+
};
46+
```
47+
48+
### Input with customizable SuggestionItem
3049

3150
The `SuggestionItem` represents the suggestion item of the `Input`
3251

packages/main/src/webComponents/Input/Input.stories.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react-vite';
22
import InputType from '@ui5/webcomponents/dist/types/InputType.js';
33
import ValueState from '@ui5/webcomponents-base/dist/types/ValueState.js';
44
import employeeIcon from '@ui5/webcomponents-icons/dist/employee.js';
5+
import { useState } from 'react';
56
import { Icon } from '../Icon/index.js';
67
import { SuggestionItem } from '../SuggestionItem/index.js';
78
import { SuggestionItemGroup } from '../SuggestionItemGroup/index.js';
@@ -28,6 +29,27 @@ type Story = StoryObj<typeof meta>;
2829

2930
export const Default: Story = {};
3031

32+
export const FullyControlled: Story = {
33+
render(args) {
34+
const [value, setValue] = useState('');
35+
return (
36+
<>
37+
<Input
38+
{...args}
39+
value={value}
40+
onInput={(e) => {
41+
e.preventDefault();
42+
args.onInput(e);
43+
if (/^[a-zA-Z]*$/.test(e.target.value)) {
44+
setValue(e.target.value);
45+
}
46+
}}
47+
/>
48+
</>
49+
);
50+
},
51+
};
52+
3153
export const WithSuggestionItem: Story = {
3254
name: 'with SuggestionItem',
3355
args: {

0 commit comments

Comments
 (0)