To handle CRUD in a form component with React and Redux, we wrap the redux Provider around our app.
Then we can use Redux form to save form values in our Redux store.
For instance, we write
import React from "react";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { modelReducer, formReducer } from "react-redux-form";
import MyForm from "./components/my-form-component";
const store = createStore(
combineReducers({
user: modelReducer("user", { name: "" }),
userForm: formReducer("user"),
})
);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<MyForm />
</Provider>
);
}
}
to call createStore to create our store with the reducers created from combineReducers.
Then we write
mport React from "react";
import { connect } from "react-redux";
import { Field, Form } from "react-redux-form";
class MyForm extends React.Component {
handleSubmit(val) {
// ...
console.log(val);
}
render() {
let { user } = this.props;
return (
<Form model="user" onSubmit={(val) => this.handleSubmit(val)}>
<h1>Hello, {user.name}!</h1>
<Field model="user.name">
<input type="text" />
</Field>
<button>Submit!</button>
</Form>
);
}
}
export default connect((state) => ({ user: state.user }))(MyForm);
to add the Form component in MyForm to create a form with redux form.
And we add the Field component to add a field.
We set model to the path of the item we save in the store.