Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat(new-hope): fix textfield react-hook-form change event for first … #1541

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/plasma-new-hope/src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { css } from '@linaria/core';
import type { RootProps } from '../../engines';
import { cx } from '../../utils';
import { useOutsideClick } from '../../hooks';
import { createEvent } from '../../utils/syntheticEvent';

import type { ChipValues, TextFieldPrimitiveValue, TextFieldProps, TextFieldRootProps } from './TextField.types';
import { base as sizeCSS } from './variations/_size/base';
Expand Down Expand Up @@ -257,11 +258,21 @@ export const textFieldRoot = (Root: RootProps<HTMLDivElement, TextFieldRootProps
}, [isChipEnumeration, values]);

useEffect(() => {
console.log('Init Value');
setHasValue(Boolean(rest?.defaultValue));
const event = createEvent(inputRef);
if (event) {
handleChange(event);
}
}, [rest.defaultValue]);

useEffect(() => {
console.log('Set Value');
setHasValue(Boolean(outerValue) || Boolean(inputRef?.current?.value));
const event = createEvent(inputRef);
if (event) {
handleChange(event);
}
}, [outerValue, inputRef?.current?.value]);

const innerOptional = Boolean(required ? false : optional);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ const StoryDemo = ({ enableContentLeft, enableContentRight, view, ...rest }: Sto

return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '2rem', width: '70%', margin: '0 auto' }}>
<div>{text}</div>
<TextField
{...rest}
enumerationType="plain"
Expand Down
43 changes: 43 additions & 0 deletions packages/plasma-new-hope/src/utils/syntheticEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { RefObject } from 'react';

export const createEvent = (ref: RefObject<HTMLInputElement>) => {
if (ref.current) {
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { writable: false, value: ref.current });
const syntheticEvent = createSyntheticEvent(event) as React.ChangeEvent<typeof ref.current>;
console.log(syntheticEvent);
return syntheticEvent;
}

return null;
};

export const createSyntheticEvent = <T extends Element, E extends Event>(event: E): React.SyntheticEvent<T, E> => {
let isDefaultPrevented = false;
let isPropagationStopped = false;
const preventDefault = () => {
isDefaultPrevented = true;
event.preventDefault();
};
const stopPropagation = () => {
isPropagationStopped = true;
event.stopPropagation();
};
return {
nativeEvent: event,
currentTarget: event.currentTarget as EventTarget & T,
target: event.target as EventTarget & T,
bubbles: event.bubbles,
cancelable: event.cancelable,
defaultPrevented: event.defaultPrevented,
eventPhase: event.eventPhase,
isTrusted: event.isTrusted,
preventDefault,
isDefaultPrevented: () => isDefaultPrevented,
stopPropagation,
isPropagationStopped: () => isPropagationStopped,
persist: () => {},
timeStamp: event.timeStamp,
type: event.type,
};
};
123 changes: 122 additions & 1 deletion website/plasma-b2c-docs/docs/form/ReactHookForm.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,125 @@ export function App() {

```

[Пример CodeSendBox](https://codesandbox.io/p/sandbox/plasma-b2c-example-forked-qcdryl?workspaceId=e0ca307f-e975-46db-8d32-7c7a7a3970e4)
[Пример CodeSendBox](https://codesandbox.io/p/sandbox/plasma-b2c-example-forked-qcdryl?workspaceId=e0ca307f-e975-46db-8d32-7c7a7a3970e4)




# React Hook Form

Компоненты поддерживают работу с библиотекой [React Hook Form](https://react-hook-form.com/)



```tsx live

import { useForm } from "react-hook-form";
import React, { useState, useEffect } from "react";
import {
Button,
TextField,
TextArea,
Checkbox,
Switch,
Radiobox,
RadioGroup,
Slider,
DatePicker,
DatePickerRange,
} from "@salutejs/plasma-b2c";


export function App() {
const langName = "language";
const radioboxItems = [
{ langName, value: "c", label: "C", disabled: false },
{ langName, value: "cpp", label: "C++", disabled: false },
{ langName, value: "assembly", label: "Assembly", disabled: false },
];

const [defaultValues, setDefaultValues] = useState({
textfield: "2",
textarea: "Bim",
checkbox: true,
switch: true,
radiobox: "c",
slider: 20,
sliderdouble: [10, 20],
datepicker: "2022-08-19T23:15:30.000Z",
});

useEffect(() => {
setTimeout(() => {
setDefaultValues({
textfield: "1",
textarea: "Bim 2",
checkbox: false,
switch: false,
radiobox: "cpp",
slider: 30,
sliderdouble: [10, 50],
datepicker: "2024-08-19T23:15:30.000Z",
});
}, 4000);
}, [setDefaultValues]);

const { register, handleSubmit } = useForm({ values: defaultValues });
const onSubmit = (data) => {
console.log(data);
};

return (
<form
onSubmit={handleSubmit(onSubmit)}
style={{ display: "flex", flexDirection: "column", gap: "20px" }}
>
<TextField {...register("textfield")} placeholder="Textfield" />
<TextArea
{...register("textarea")}
defaultValue={defaultValues.textarea}
autoResize
placeholder="Textarea"
/>
<Checkbox {...register("checkbox")} label="Checkbox" />
<Switch {...register("switch")} label="Switch" labelPosition="after" />
<RadioGroup aria-labelledby="radiogroup-title-id">
<div
id="radiogroup-title-id"
style={{ margin: "1rem 0", fontWeight: "600" }}
>
Выберите язык программирования для изучения.
</div>
{radioboxItems.map((item) => (
<Radiobox
{...register("radiobox")}
key={item.value}
value={item.value}
label={item.label}
disabled={item.disabled}
/>
))}
</RadioGroup>
<Slider
{...register("slider")}
label="Slider"
type="single"
defaultValue={defaultValues.slider}
min={0}
max={100}
/>
<Slider
{...register("sliderdouble")}
label="Slider Double"
type="double"
defaultValue={defaultValues.sliderdouble}
min={0}
max={100}
/>
<DatePicker {...register("datepicker")} label="DatePicker" />
<Button type="submit">Отправить</Button>
</form>
);
}

```
Loading