A
A
Anastasia2020-10-20 12:17:42
typescript
Anastasia, 2020-10-20 12:17:42

I need the form fields to be cleared when the data is not successfully sent to the back, how to do this in the component (isClear comes from redux as a signal)u)?

spoiler

import React, { useState } from 'react';
import { createSelector } from 'reselect';
import { connect } from 'react-redux';
import './CustomInput.css';
import { RootState } from '../common/root-reduser';

interface CustomInputProps {
name: string;
type: string;
label: string | null;
placeholder: string;
value: string;
onChange: (data: CallbackCustomInputData) => void;
isClear?: boolean;
}

export interface CallbackCustomInputData {
name: string;
value: string;
}

const clearSelector = (state: RootState) => state.user.isClear;

const getClear = createSelector(clearSelector, (i) => i);

const CustomInput: React.FC = (props: CustomInputProps) => {
const [checked, setChecked] = useState(false);
const handleKeyDown = (event: React.KeyboardEvent) => {
const { key } = event;
if (key === ' ' || key === 'Enter') {
setChecked(!checked);
}
};
return (

htmlFor={`${props.type}-${props.label}`}
className={
props.type === 'checkbox'
? 'wrapper-input__label-checkbox'
: 'wrapper-input__label-custom'
}
>
{props.label}

{props.type !== 'checkbox' ? (


name={props.name}
className="wrapper-input__custom-input"
id={`${props.type}-${props.label}`}
type={props.type}
placeholder={props.placeholder}
value={props.isClear && props.value}
defaultValue={props.value}
onChange={(event: React.ChangeEvent) =>
props.onChange({ name: props.name, value: event.currentTarget.value })
}
/>

) : (

role="checkbox"
aria-checked={checked}
aria-labelledby={`${props.type}-${props.label}`}
tabIndex={0}
className={`square outline icon column__icon ${checked ? 'check' : ``}`}
onClick={() => setChecked(!checked)}
onKeyDown={handleKeyDown}
/>
name={props.name}
className="wrapper-input__custom-input"
id={`${props.type}-${props.label}`}
type={props.type}
placeholder={props.placeholder}
checked={checked}
onChange={() => setChecked(!checked)}
/>

)}

);
};

CustomInput.defaultProps = {
isClear: undefined,
};

export default connect((state: RootState) => {
return {
isClear: getClear(state),
};
}, null)(CustomInput);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xenonhammer, 2020-10-20
@KnopkaNen

If the form fields are controllable, then you need to give each field a defaultValue=''

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question