Use useRef to call submitForm from a parent component - reactjs

I am using react hooks and useRef to call a child method from the parent (see here: Call child method from parent)
Specifically, I am trying to call the formik submitForm method which is located in my child component from my parent component. I know there are other ways to do this (React Formik use submitForm outside <Formik />) but i would really like to use useRef.
const Auth1 = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
handleSubmit() {
///////////formik submitForm function goes here
}
}));
return(
<div>
<Formik
initialValues={props.initValues}
validationSchema={Yup.object().shape({
name: Yup.string().required('Required'),
})}
onSubmit={(values, actions) => {
console.log(values)
}}
render={({ values }) => (
<Form>
<Field
name="name"
value={values.name}
component={TextField}
variant="outlined"
fullWidth
/>
</Form>
)}
/>
</div>
)
})
There must be a way to bind the submitForm function out of the component and into the body of my Auth1 component, but imnot quite too sure how.
Any help is greatlly appreciated, thanks!

You can pull the handleSubmit function out of the useImperativeHandle call the exposed method from parent using ref
const Auth1 = forwardRef((props, ref) => {
const handleSubmit = (values, actions) => {
///////////formik submitForm function goes here
}
useImperativeHandle(ref, () => ({
handleSubmit
}), []);
return(
<div>
<Formik
initialValues={props.initValues}
validationSchema={Yup.object().shape({
name: Yup.string().required('Required'),
})}
onSubmit={handleSubmit}
render={({ values }) => (
<Form>
<Field
name="name"
value={values.name}
component={TextField}
variant="outlined"
fullWidth
/>
</Form>
)}
/>
</div>
)
})
Now from the parent you could have
const Parent = () => {
const authRef = useRef(null);
...
const callSubmit = () => {
authRef.current.handleSubmit(values, actions);
}
return (
<>
{/* */}
<Auth1 ref={authRef} />
</>
)
}

Related

How to implement custom handleOnChange in Formik

as I mentioned in the title, how can I implement my custom handleChange function?
Here's standard example:
const MyTextField = ({ label, ...props }) => {
const [field, meta, helpers] = useField(props);
return (
<>
<input {...field} {...props} />
</>
);
};
const Example = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{}}
onSubmit={() => {}}
>
{() => (
<Form>
<MyTextField name="firstName" type="text" label="First Name" />
</Form>
)}
</Formik>
</div>
);
Let's say I have onChange function:
const customHandle = (e) => {
console.log('Custom Function')
}
How can I combine my custom function with Formik
EDIT.
Explanation: I will not use form in my case, I just want to have simple input which will update a 'redux or something else state managmenent'

Is it possible to simple-react-code-editor as a Formik field component?

Trying to get this form field component to take a simple-react-code-editor:
not sure if I'm going about this the right way by trying to pass props form the useField hook, but it works for textfield tags, so thought the same method could apply to this as well. Although, I get the feeling the onValueChange callback is different from the onChange callback that this component doesn't have. Is there a way to add it somehow?
Editor Component:
const MyEditor = ({value, onChange}) => {
const highlight = (value) => {
return(
<Highlight {...defaultProps} theme={theme} code={value} language="sql">
{({ tokens, getLineProps, getTokenProps }) => (
<>
{tokens.map((line, i) => (
<div {...getLineProps({ line, key: i })}>
{line.map((token, key) => (
<span {...getTokenProps({ token, key })} />
))}
</div>
))}
</>
)}
</Highlight>
)
};
return (
<Editor
value={value}
onValueChange={onChange}
highlight={highlight}
padding={'40px'}
style={styles.root}
/>
);
}
export default MyEditor;
Form with Field Component as MyEditor (tried using useField hook):
const FormQueryTextBox = ({...props}) => {
const [field] = useField(props);
return (
<MyEditor onChange={field.onChange} value={field.value}/>
)
}
const validationSchema = yup.object({
query_name: yup
.string()
.required()
.max(50)
});
const AddQueryForm = () => {
return (
<div>
<Formik
validateOnChange={true}
initialValues={{
query:""
}}
validationSchema={validationSchema}
onSubmit={(data, { setSubmitting }) => {
console.log(data);
}}
>
{() => (
<Form>
<div>
<Field
placeholder="query name"
name="query_name"
type="input"
as={TextField}
/>
</div>
<div>
<Field
name="query"
type="input"
as={FormQueryTextBox}
/>
</div>
</Form>
)}
</Formik>
</div>
)
}
components render without errors, but as I type the text doesn't appear.
I figured out that I just need to customize my onChange with the setter from the useFormikContext hook like this:
const FormQueryTextBox = ({...props}) => {
const [field] = useField(props);
const { setFieldValue } = useFormikContext();
return (
<MyEditor {...field} {...props} onChange={val => {
setFieldValue(field.name, val)
}}/>
)
}

enzyme: find() formik components inside an anonymous function

I am using enzyme for testing react components.
I have a formik form with this structure:
Form.js
export class Form extends Component {
constructor(props) {
//...
}
render() {
<Formik
inititalValues={{
//...
}}
onSubmit={(values, { resetForm }) => {
//...
//...
}}
onReset = {(values, formProps) => {
//...
}}
validationSchema={
//...
}>
{
(props) => {
const {values, errors, handleSubmit} = props;
return (
<form onSubmit={handleSubmit}>
<input type='text' name='email' />
<input type='password' name='password' />
<button type='submit'>Submit</button>
</form>
)
}
}
</Formik>
}
}
How do i use enzyme's find() method to get those input fileds?
I can get the main <Formik> component but can't get the input fields inside that anonymous function. Any help would be appriciated.
You can use dive() to expand the nested form.
shallow(<Form {...props} />)
.find(Formik)
.dive()
You can also trigger Formik props directly using prop(key)
shallow(<Form {...props} />)
.find(Formik)
.prop('onSubmit')(args)

How do I access current value of a formik field without submitting?

How do I access value of the SelectField named countryCode in my React component? Use case is that validation scheme should change according to the countryCode.
<Formik
onSubmit={(values, actions) => this.onSubmit(values, actions.setFieldError)}
validationSchema={() => this.registrationValidationSchema()}
enableReinitialize={true}
initialValues={this.props.initialData}
>
<Form>
<Field
name="countryCode"
component={SelectField}
label="Country"
labelClassName="required"
options={Object.entries(sortedCountryList).map(x => ({
value: x[1][1],
label: x[1][0]
}))}
/>
</Form>
</Formik>
I have tried to access it via a ref, then via this.props.values (as suggested in getFieldValue or similar in Formik) but both return just undefined or null. My props don't have any "values" field.
EDIT: Found an ugly way: document.getElementsByName("countryCode")[0].value. A better way is appreciated.
You can use ref, if you need the values outside formik
const ref = useRef(null);
const someFuncton = () => {
console.log(ref.current.values)
}
<Formik
innerRef={ref}
onSubmit={(values, actions) => this.onSubmit(values,
actions.setFieldError)}
validationSchema={() => this.registrationValidationSchema()}
enableReinitialize={true}
initialValues={this.props.initialData}
/>
<form></form>
</Formik>
You can access values like this:
<Formik
onSubmit={(values, actions) => this.onSubmit(values,
actions.setFieldError)}
validationSchema={() => this.registrationValidationSchema()}
enableReinitialize={true}
initialValues={this.props.initialData}
>
{({
setFieldValue,
setFieldTouched,
values,
errors,
touched,
}) => (
<Form className="av-tooltip tooltip-label-right">
// here you can access to values
{this.outsideVariable = values.countryCode}
</Form>
)}
</Formik>
you can get it from formik using the Field comp as a wrapper
import React, { ReactNode } from 'react';
import { Field, FieldProps } from 'formik';
(...other stuffs)
const CustomField = ({
field,
form,
...props
}) => {
const currentError = form.errors[field.name];
const currentField = field.name; <------ THIS
const handleChange = (value) => {
const formattedDate = formatISODate(value);
form.setFieldValue(field.name, formattedDate, true);
};
const handleError = (error: ReactNode) => {
if (error !== currentError) {
form.setFieldError(field.name, `${error}`);
}
};
return (
<TextField
name={field.name}
value={field.value}
variant="outlined"
helperText={currentError || 'happy helper text here'}
error={Boolean(currentError)}
onError={handleError}
onChange={handleChange}
InputLabelProps={{
shrink: true,
}}
inputProps={{
'data-testid': `${field.name}-test`, <---- very helpful for testing
}}
{...props}
/>
</MuiPickersUtilsProvider>
);
};
export default function FormikTextField({ name, ...props }) {
return <Field variant="outlined" name={name} component={CustomField} fullWidth {...props} />;
}
it is very simple just do console.log(formik.values) and you will get all the values without submitting it.

ReactJS - How can I set a value for textfield from material-ui?

I have a selectField and I want to set a value on it. Let say I type on it and when I click a button, the button will call a function that will reset the value of the textfield?
<TextField hintText="Enter Name" floatingLabelText="Client Name" autoWidth={1} ref='name'/>
You can do it in this way
export default class MyCustomeField extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Enter text',
};
}
handleChange = (event) => {
this.setState({
value: event.target.value,
});
};
handleClick = () => {
this.setState({
value:'',
});
};
render() {
return (
<div>
<TextField
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Reset Text</button>
</div>
);
}
}
It's maintained that the right way is to have the component be controlled in a scenario like the accepted answer there, but you can also control the value in this gross and culturally unacceptable way.
<TextField ref='name'/>
this.refs.name.getInputNode().value = 'some value, hooray'
and you can of course retrieve the value like so
this.refs.name.getValue()
Instead of using ref you should use inputRef
const MyComponent = () => {
let input;
return (
<form
onSubmit={e => {
e.preventDefault();
console.log(input.value);
}}>
<TextField
hintText="Enter Name"
floatingLabelText="Client Name"
autoWidth={1}
inputRef={node => {
input = node;
}}/>
</form>
)
};
Here is a short simple React Hook version of the answer
export default function MyCustomeField({
initialValue= '',
placeholder= 'Enter your text...'
}) {
const [value, setValue] = React.useState(initialValue)
return (
<div>
<TextField
placeholder={placeholder}
value={value}
onChange={e => setValue(e.target.value)}
/>
<button onClick={() => setValue(initialValue)}>Reset Text</button>
</div>
);
}
I would suggest to do a little wrap on the original MUI TextField.
export default function ValueTextField(props) {
const [value, setValue] = useState(props.value);
return (
<TextField {...props} onChange={(event) => setValue(event.target.value)} value={value}/>
);
}
Now you can use your own ValueTextField component now.
<ValueTextField value={"hello world"}></ValueTextField>
I prefer this way to assign the state variables:
<TextField value={mobileNumber}
onChange={e => { this.setState({ mobileNumber: e.target.value }) }}
className={classes.root}
fullWidth={true}
label={t('mobile number')} />

Resources