Redux-Form reset field with custom component - reactjs

I'm very new to react, redux and redux-form (and frontend in general :D).
I have a component with a form and a Field with a custom component.
const SomeComponent = ({ .. }) => (
<div>
...
<Field
name="someName"
component="select"
...
/>
<Field
name="someName"
component={CustomComponent}
...
/>
</div>
)
When I create this component:
<SomeComponent
form={form}
onSubmitSuccess={(data, dispatch) => dispatch(reset(form))} />
The first field is cleared correctly but the second it's not. What do I have to do to make my CustomComponent aware of the reset?

Related

React Admin - overiding handleSubmit on SimpleForm

What I want to achieve is this but using react admin SimpleForm instead of Form:
import React, { useState } from "react";
export function NameForm(props) {
const [name, setName] = useState("");
const handleSubmit = (evt) => {
evt.preventDefault();
alert(`Submitting Name ${name}`)
}
return (
<form onSubmit={handleSubmit}>
<label>
Frirst Name:
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
When I try the same pattern, i.e.:
<SimpleForm onSubmit={handleSubmit}>
it never reaches the handleSubmit function. I also tried:
<SimpleForm handleSubmit={handleSubmit}>
But again no joy.
The react admin docs here say:
Finally, it receives a handleSubmit function as prop, to be called with the updated record as an argument when the user submits the form.
Unfortunately being new to react this doesn't give me any clue as to what I should do to get this to work.
When you're using any third party library you need to follow their rules. Here you're using React admin library which support normal admin features like add/edit/listing etc. With minimal effort you can create admin panel.
So when you're focusing on creating form using React Admin , you can create add/edit form.
In your App.js you need to first define routing using Resource which contains create and edit attribute. In create/edit you can import your add/edit component and pass it. The example is given below. You can see dataProvider link is also provided. When you'll create edit form it will take data from there
// in src/App.js
import * as React from "react";
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
import { PostCreate, PostEdit } from './posts';
const App = () => (
<Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
<Resource name="posts" create={PostCreate} edit={PostEdit} />
</Admin>
);
export default App;
After creating proper routing you can go to your component and can create add/edit form just like below
// in src/posts.js
import * as React from "react";
import { Create, Edit, SimpleForm, TextInput, DateInput, ReferenceManyField, Datagrid, TextField, DateField, EditButton } from 'react-admin';
import RichTextInput from 'ra-input-rich-text';
export const PostCreate = (props) => (
<Create {...props}>
<SimpleForm>
<TextInput source="title" />
<TextInput source="teaser" options={{ multiLine: true }} />
<RichTextInput source="body" />
<DateInput label="Publication date" source="published_at" defaultValue={new Date()} />
</SimpleForm>
</Create>
);
export const PostEdit = (props) => (
<Edit {...props}>
<SimpleForm>
<TextInput disabled label="Id" source="id" />
<TextInput source="title" validate={required()} />
<TextInput multiline source="teaser" validate={required()} />
<RichTextInput source="body" validate={required()} />
<DateInput label="Publication date" source="published_at" />
<ReferenceManyField label="Comments" reference="comments" target="post_id">
<Datagrid>
<TextField source="body" />
<DateField source="created_at" />
<EditButton />
</Datagrid>
</ReferenceManyField>
</SimpleForm>
</Edit>
);
React-admin injects a few props to the create and edit views: the resource name, the basePath (the root URL), the permissions, and, in the case of the edit view, the record id. That’s why you need to pass the props to the <Create> and <Edit> components.
The <Create> and <Edit> components call the dataProvider, prepare the form submit handler, and render the page title and actions.
<SimpleForm> Which you mentioned in your question is responsible for creating the form only, it's not responsible for handleSubmit operation , <Create> and <Edit> components handle that.
To know more in details follow the React Admin <Create> and <Edit> doc carefully.
So I found the solution I was looking for thanks to the answer from Saswata Pal. To achieve the effect I was looking for I changed the component so it was like this:
<Create transform={transform}>
This allowed me to grab the form result before submission and modify.
Relevant docs here:
https://marmelab.com/blog/2020/06/09/react-admin-3-6.html

can't access validate props inside component - redux form

I want to access the validate props inside the custom component,
This is my component
<Field name="firstName" validate={[ required() ]} label="First Name" component={MyCustomComponent} />
MyCustomComponent.jsx
function MyCustomComponent(props){
const isRequired = props.validate
return(<div> <span>*<span> .... </div>)
}
Can't access validate props inside mycustom component.

Updating the value of a react-final-form Field component with a onSelect function call?

I'm doing a react application with typescript and using react-final-form, I'm using some react libraries to integrate the google places and geocoder APIs: "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0"
The problem I'm having is updating the value in the react-final-form field after the user selects one of the suggestions delivered by the auto complete component on the onSelect: Below are some excerpts of the code:
onSelect Functions:
const handleCitySelect = (selectedCity: string) => {
geocodeByAddress(selectedCity)
.then(results => getLatLng(results[0]))
.then(latlng => {
setCityLatLng(latlng);
}); <-- Here I need to update the field with selectedCity
};
const handleVenueSelect = (selectedVenue: string) => {
geocodeByAddress(selectedVenue)
.then(results => getLatLng(results[0]))
.then(latlng => {
setVenueLatLng(latlng);
}); <-- Here I need to update the field with selectedVenue
};
React final form:
<FinalForm <-- react-final-form component
validate={validate}
initialValues={activity}
onSubmit={handleFinalFormSubmit}
render={({ handleSubmit, invalid, pristine }) => (
<Form onSubmit={handleSubmit} loading={loading}> <-- semantic-ui-react component
<Field
name="title"
placeholder="Title"
value={activity.title}
component={TextInput}
/>
<Field
name="description"
placeholder="Description"
rows={3}
value={activity.description}
component={TextAreaInput}
/>
<Field
component={SelectInput}
options={category}
name="category"
placeholder="Category"
value={activity.category}
/>
<Form.Group widths="equal">
<Field
component={DateInput}
name="date"
date={true}
placeholder="Date"
value={activity.date}
/>
<Field
component={DateInput}
name="time"
time={true}
placeholder="Time"
value={activity.time}
/>
</Form.Group>
<Field <-- field I need to update after the onSelect callback
component={PlaceInput}
name="city"
placeholder="City"
options={{ types: ["(cities)"] }}
value={activity.city}
onSelect={handleCitySelect}
/>
<Field <-- field I need to update after the onSelect callback
component={PlaceInput}
name="venue"
placeholder="Venue"
options={{
location: new google.maps.LatLng(cityLatLng),
radius: 1000,
types: ["establishment"]
}}
value={activity.venue}
onSelect={handleVenueSelect}
/>
<...>
The PlaceInput is a custom component that servers as a wrapper around the PlacesAutocomplete component that does the suggestions according to what the user types.
Thanks to anyone who can suggest a solution. I scoured the Internet and couldn't find a quick fix to something that I feel should be a no-brainer. If more explanations are needed please let me know or more code excerpts.
Cheers,
To set the field value, your PlaceInput needs to call input.onChange(newValue).
Also, you should not be passing a value prop to Field. That's only for checkboxes and radio buttons.

Can't submit TextField in Formik

Can't seem to find a reason why the first approach works, and the second doesn't.
Works: pastebin
Doesn't: pastebin
The difference between these two is that there's <TextField> in the second one instead of <div> and <Field>. But the examples I've seen makes the <TextField> work just fine, what am I missing?
You have to pass the component to <Field />:
<Field component={TextField} name="password">
You are now trying to use it like so:
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
render={props => (
<Form>
<TextField
id="name"
name="name"
label="Name"
value={props.values.name}
onChange={props.handleChange}
fullWidth
/>
</Form>
)}
/>
... Which should work, are you getting any errors in the console?
If that doesn't work for some reason you can try doing it via Field render props.
This snippet is taken from the Formik docs.
<Formik
...
<Field
name="lastName"
render={({ field }) => (
<input {...field} placeholder="password" />
)}
/>
...
/>
You see you can use a render props to the Field component to render a custom component if you like.
There are 3 ways to render things with <Field>.
Aside from
string-only component, each render prop is passed the same props for
your convenience.
Field's render props are an object containing:
field: An object containing onChange, onBlur, name, and value of the
field form: Formik state and helpers Any other props passed to field
See more in Formik docs here.

Cannot set initialValues on SelectField component using redux-form-material-ui

I am trying to render initialValues for a form using redux-form-material-ui. So far initialValues are working for my TextField components but not for SelectField.
I am currently passing initialValues as a prop through the parent component like this:
<PacketFilterForm initialValues={this.props.initialConfigValuesForForm} />
This is working on this case:
<Field name="name" component={TextField} hintText="Ex. Rule 1" floatingLabelText='Name of Rule'/>
However, it is not working for this case:
<Field component={SelectField} name='ethertype'>
<MenuItem key={1} value='ipv4' primaryText="IPV4" />,
<MenuItem key={2} value='ipv6' primaryText="IPV6" />
</Field>
How can I set an initialValues for this SelectField component?
try in your componentWillMount() because Form component of redux form works with name and value
componentWillMount() {
this.props.change('ethertype', 'ipv6')
}

Resources