We have built a React Application that connects with Redux, then filter with input text and sort list of items. In this tutorial, we continue to create a Form for adding item to list using react-redux.
Contents
Example Overview
Our app has add item form. If we fill in title, author(, description), published year and click on Add Book button, the list of Book items will be updated immediately.
Add Item Form
Context
Remember that our App state is like this:
const demoState = { books: [ { id: '123abcdefghiklmn', title: 'Origin', description: 'Origin thrusts Robert Langdon into the dangerous intersection of humankind’s two most enduring questions.', author: 'Dan Brown', published: 2017 } ], filters: { text: 'ori', sortBy: 'published', // published or title startYear: undefined, endYear: undefined } }; |
We also have addBook action:
// actions/books.js export const addBook = ({ title = '', description = '', author = '', published = 0 } = {}) => ({ type: 'ADD_BOOK', book: { id: uuid(), title, description, author, published } }); |
=> dispatch(addBook(bookFromForm))
will add Book to the List.
Solution
We need:
– a Form to fill in Book fields => create BookForm Component with form
and onSubmit
function. BookForm Component has its own state to update data from form
elements.
– an AddBook Component to contain BookForm Component => it connects with Redux to pass dispatch(addBook)
to BookForm Component.
Practice
Create BookForm Component
BookForm.js
import React from 'react'; export default class BookForm extends React.Component { constructor(props) { super(props); this.onTitleChange = this.onTitleChange.bind(this); this.onAuthorChange = this.onAuthorChange.bind(this); this.onDescriptionChange = this.onDescriptionChange.bind(this); this.onPublishedChange = this.onPublishedChange.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { title: '', author: '', description: '', published: 0, error: '' }; } onTitleChange(e) { const title = e.target.value; this.setState(() => ({ title: title })); } onAuthorChange(e) { const author = e.target.value; this.setState(() => ({ author: author })); } onDescriptionChange(e) { const description = e.target.value; this.setState(() => ({ description: description })); } onPublishedChange(e) { const published = parseInt(e.target.value); this.setState(() => ({ published: published })); } onSubmit(e) { e.preventDefault(); if (!this.state.title || !this.state.author || !this.state.published) { this.setState(() => ({ error: 'Please set title & author & published!' })); } else { this.setState(() => ({ error: '' })); this.props.onSubmitBook( { title: this.state.title, author: this.state.author, description: this.state.description, published: this.state.published } ); } } render() { return ( <div> {this.state.error && <p className='error'>{this.state.error}</p>} <form onSubmit={this.onSubmit} className='add-book-form'> <input type="text" placeholder="title" autoFocus value={this.state.title} onChange={this.onTitleChange} /> <br /> <input type="text" placeholder="author" value={this.state.author} onChange={this.onAuthorChange} /> <br /> <textarea placeholder="description" value={this.state.description} onChange={this.onDescriptionChange} /> <br /> <input type="number" placeholder="published" value={this.state.published} onChange={this.onPublishedChange} /> <br /> <button>Add Book</button> </form> </div> ); } } |
This Component uses onSubmitBook()
received from its parent – AddBook Component.
Create AddBook Component
AddBook.js
import React from 'react'; import BookForm from './BookForm'; import { connect } from 'react-redux'; import { addBook } from '../actions/books'; const AddBook = (props) => ( <div> <h3>Set Book information:</h3> <BookForm onSubmitBook={(book) => { props.dispatch(addBook(book)); props.history.push('/'); }} /> </div> ); export default connect()(AddBook); |
After adding Book, our app goes to the main page to show list of Book items with props.history.push('/')
.
Run and Check Result
app.js
import React from 'react'; import ReactDOM from 'react-dom'; import AppRouter from './routers/AppRouter'; import getAppStore from './store/store'; import { addBook } from './actions/books'; import { filterText, startYear, endYear, sortBy, clear } from './actions/filters'; import getVisibleBooks from './selectors/books'; import './styles/styles.scss'; import { Provider } from 'react-redux'; const store = getAppStore(); store.dispatch(addBook({ title: 'Origin', description: 'Origin thrusts Robert Langdon into the dangerous intersection of humankind’s two most enduring questions.', author: 'Dan Brown', published: 2017 })); store.dispatch(addBook({ title: 'Harry Potter and the Goblet of Fire', description: 'A young wizard finds himself competing in a hazardous tournament between rival schools of magic, but he is distracted by recurring nightmares.', author: 'J. K. Rowling', published: 2000 })); store.dispatch(addBook({ title: 'Harry Potter and the Deathly Hallows', description: 'The seventh and final novel of the Harry Potter series.', author: 'J. K. Rowling', published: 2007 })); store.dispatch(addBook({ title: 'The 100-Year-Old Man Who Climbed Out the Window and Disappeared', author: 'Jonas Jonasson', published: 2009 })); const template = ( <Provider store={store}> <AppRouter /> </Provider> ); ReactDOM.render(template, document.getElementById('app')); |
Check Result
– click on AddBook, fill in Book fields:
– Click on Add Book button, the Browser will go to main page with new Book:
Source Code
For running:
– yarn install
– yarn run dev-server
or yarn run build
, then yarn run serve
.
спасибо интересное чтиво
fktrpr94f
For over a decade, JeffryChandra.biz has been breaking new ! ground in bringing to the boating community a wide selection of very competitively priced new and pre-owned boats and Jetski sales. jeffrychandra.biz offering boat rental and storage. With our 125 wet slips, 150 dry storage and launching services, jeffrychandra.biz is the perfect place to store your boat. We are located is in Surabaya, Jawa Timur – Indonesia.
Chat freely and without restrictions.
Join 100% Free.
Eskadron is among the most appreciated equestrian brands on the world that focuses primarily on the production of highquality equestrian clothing and equipment. This German concern was founded by Pikeur wanting to fulfill up with the jockeys’ demands, have been looking for professional but also stylish equestrian accessories. Thus, what makes Eskadron therefore special and why their selections are so popular with riders?Eskadron Why do riders from all around the world love this new brand?
Eskadron is tremendously popular with horse-riding lovers for a dozen or more years today. This brand’s products are characterized by their own supreme quality attention for detail. Eskadron can be valued for their unique practicality, elegance, innovativeness in their projects, modern layout, and availability. The brand’s offer includes both professional ones and items for amateur riders. So, you can find basic equestrian clothing, professional design, and assorted accessories necessary for your appropriate saddling of a horse. Eskadron offers saddle fabrics, halters, rugs, bell boots for horses, vases, fly hats, drapes, but in addition hoodies, tshirts, breeches, even reveal coats. These products include the European Union, which additionally verifies their own quality.Eskadron’s collections
Eskadron has many collections. Many are seasonal, many others are always accessible their offer. The most Well-known collections of the brand are:
Vintage Sports – launched twice a year, this line consists exclusively of horse riding equipment. Services and products out of this collection are extremely simple, in conventional soft colours but at the exact same time quite tasteful.
Platinum Card – launches once annually for people who prefer conventional solutions. You’ll mostly find gray and black colors together with delicate picture themes.
Young Star – lineup for children that begin their experience with horse riding. It’s basic horse riding accessories in bright colours and extraordinary patterns.
Equestrian Fanatics – clothing line made for riders who like to stand out. Available jackets, hoodies, and backpacks successfully combine casual clothing with equestrianism.
Classic offer – Their steady offer of clothing, equipment, and accessories. You can find products useful for training and regular rides but also elegant reveal clothing.
Eskadron can be a new used by riders from all around the world. For the comfort of riding and safety both yours and your horse’s, it is worth buying high quality articles, which may allow you to fully enjoy this exceptional sport.
Привед
Howdy! Thank You for this..waw. As a Mojoheadz Label …
W dzisiejszych czasach Obecnie handel sprzedaż transakcja zakupowa Jest czynnością prostszą łatwiejszą sprawniejszą dostępniejszą niż kiedykolwiek wcześniej w dobie bez internetu. Możliwość Sposobność prowadzenia handlu sprzedaży sklepu przez internet otwiera poszerza horyzonty granice i pozwala na wykonywanie zagranicznych transakcji sprzedaży zagranicznej działań na światową skalę. Przesyłki do Rumunii Paczki kurierskie do Rumunii Przesyłanie zakupionych przedmiotów do Rumunii to kolejny krok stopień szczebel w rozwoju modernizacji ulepszaniu sklepu internetowego handlu internetowego. Dzięki nam Z naszą pomocą Dzięki naszemu wsparciu Z naszymi możliwościami możesz z łatwością łatwo i szybko bez trudu bez kłopotu wprowadzić takie przesyłki do swojej oferty sklepu internetowego handlu internetowego. Zobacz Spójrz Patrz jakie to proste łatwe szybkie
Przesyłki do Rumunii Paczki do Rumunii Kurier do Rumunii Przesyłki kurierskie do Rumunii Nadawanie paczek kurierskich do Rumunii
umacnia ulepsza usprawnia prowadzenie sklepu internetowego handlu internetowego. Oferujemy Proponujemy kompleksową najlepszą ogólnie dostępną pomoc w prowadzeniu sklepu internetowego z paczkami do Rumunii sprzedaży towaru ze sklepu internetowego do Rumunii. Dzięki szerokiej wiedzy i ogromnemu doświadczeniu dużym zasobom wiedzy i doświadczeniu każdego dnia na co dzień w codziennych obowiązkach możemy potrafimy pomagać wspierać każdego, kto zdecyduje się podejmie dobrą decyzję i postawi na paczki kurierskie do Rumunii przesyłki kurierskie do Rumunii.
Nasza frima Nasza działalność pomaga w odbieraniu paczek odbiorze przesyłek odbieraniu nadań kurierskich, przyjmowaniu zwrotów obsłudze zwrotów przyjęciu zwróconych przesyłek kurierskich, oraz a także a dodatkowo a ponadto odbieramy przyjmujemy zapłatę opłatę w rumuńskich lejach rumuńskiej walucie rumuńskich stawkach walucie obowiązującej w Rumunii. Dzięki nam Z naszą pomocą w łatwy i szybki sposób pokierujesz swoim biznesem internetowym poprowadzisz swój sklep w sieci i rozwiniesz poszerzysz swoją działalność ofertę na światową międzynarodową skalę.
Zaufaj najlepszy i pozwól daj sobie pomóc. Udowodnimy Pokażemy Ci, że przesył nadawanie wysyłanie sprzedawanie paczek towarów poza granice za granicę poza Polskę może być może okazać się łatwiejsze prostsze szybsze sprawniejsze niż to prowadzone w kraju dostępne w Polsce działające na terenie naszego Państwa Jesteśmy po to działamy po to Zostaliśmy stworzeni po to aby każdego dnia na co dzień pomagać takim firmom tego typu firmom jak Twoja. Nie szukaj niesprawdzonych kurierów Nie marnuj czasu na przeglądanie internetu w poszukiwaniu innych nie trać cennych godzin na znalezienie odpowiedniego kuriera wybierz zaufaj tym, na których możesz polegać.
Awesome mo = ‘modus operandi’ of expression. Attend to it up!
schirrmacher
Privet
Astonishing personality of expression. Attend to it up!
Hello i am new user and i would to ask you, How to disable avatar?
Hello i am new user and i would to ask you, How to disable a pm?
godnotab.net
www-hydraruzxpnew4af.net
hydraruzxpnew4afi.net – Hydraruzxpnew4af Добро пожаловать на официальный сайт Гидра.