Get Param from Url & create Edit Item Form – react-redux example

We have built a React Application that connects with Redux, then filter with input text and sort list of items. We also created Form for adding new item. In this tutorial, we’re gonna use that form to edit and update item with id param getting from Url using react-redux and React Router v4.

Example Overview

When clicking on any item, the app will bring us to a Form (like add item form).
Now we can edit item and click on Add Book button, the list of Book items will be updated immediately.

edit-item-form-react-redux-example-goal

How to Get Param from Url & create Edit Item Form

Context

Remember that our App state is like this:

We have had BookForm Component that has its own state for Book fields and onSubmit() method:

We also have Router to route edit Book item by its id:

And each Book item has enough data that includes id:

Solution

We need:
– url for each Book item including id => inside Book item, add React Link with attribute to={/book/${id}}.
– ‘editBook’ action => create new Action in actions/books folder with type: 'EDIT_BOOK'. This action need 2 parameters id and updates that contains Book fields.
– a form containing Book fields => re-use BookForm Component as child in EditBook Component. It connects with Redux to pass dispatch(editBook) to BookForm Component.
– the form should have Book fields to be filled already => BookForm state get data from props that is passed from EditBook Component.

Practice

Add Link for each Item

Open components/Book.js, cover Book ‘title-published’ with Link:

Create new Action

Open actions/books.js, add action creator named editBook with id, updates as input parameters:

Add case for Book Reducer

Add Form for editing item

Inside components/EditBook.js:
– use react-redux connect() with mapStateToProps to get Book item by id form url (props.match.params.id)
– add BookForm Component with props including:
+ the Book above
+ onSubmitBook() function that contains dispatch(editBook(id,book))

Initialize Form elements with Book fields

BookForm state will be initialized by props that is received from EditBook Component.
components/BookForm.js:

Run and Check Result
app.js

Check Result

– Click on a Book title:

edit-item-form-react-redux-example-goal

– Change something and check result:

edit-item-form-react-redux-example-result

Source Code

ReactRedux-editItem-form

For running:
yarn install
yarn run dev-server or yarn run build, then yarn run serve.

By JavaSampleApproach | April 19, 2018.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*