I am working on the library project. Users can add books to the library. So, I have created the form to add a book. The form contains from the name, author, publisher, pages, ISBN and info fields. I have created the dropdown component for authors and publishers, so the user can choose from this component:
import AuthorsService from './AuthorsService'
const authorsService = new AuthorsService();
class AuthorsDropDown extends Component {
constructor(props) {
super(props);
this.state = {
authors: [],
};
}
componentDidMount() {
var self = this;
authorsService.getAuthors().then(function (result) {
self.setState({ authors: result});
});
}
render() {
return (
<div className="form-group col-sm-4">
<label>Author:</label>
<select className="form-control" onChange={(ev) => this.props.onChange(ev.target.value)}>
{this.state.authors.map( a =>
<option key={a.id} value={a.id}>{a.first_name + ' '+a.last_name }
</option>)
}
</select>
</div>
);
}
}
export default AuthorsDropDown;
I have assigned initial value for author.id and publisher.id fields in parent component as null, but, these fields only got their values after dropdown changes (i.e after onChange is fired). I have no idea how to set the value to them on rendering (i.e. initialization state). Here is the parent component:
import React, { Component } from "react";
import BookService from "./BooksService";
import AuthorsDropDown from "./AuthorsDropDown";
import PublishersDropDown from "./PublishersDropDown";
const bookService = new BookService();
class BookCreateUpdate extends Component {
constructor(props) {
super(props);
this.state = {
author:{id:null},
publisher:{id:null}
}
this.handleSubmit = this.handleSubmit.bind(this);
this.onChangeAuthor = this.onChangeAuthor.bind(this);
this.onChangePublisher = this.onChangePublisher.bind(this);
}
onChangeAuthor(new_author_id){
this.setState({author:{id:new_author_id}});
}
onChangePublisher(new_publisher_id){
this.setState({publisher:{id:new_publisher_id}});
}
handleCreate() {
alert(this.state.author.id);
bookService
.createBook({
name: this.refs.name.value,
author: this.state.author,
publisher: this.state.publisher,
page: this.refs.pages.value,
inventor_number: this.refs.inventor_number.value,
description: this.refs.description.value
})
.then(result => {
alert("The book is added!");
})
.catch(() => {
alert("Error!!");
});
}
handleUpdate(pk) {
bookService
.updateBook({
pk: pk,
name: this.refs.name.value,
author: this.refs.author,
publisher: this.refs.publisher,
pages: this.refs.pages.value,
description: this.refs.description.value
})
.then(result => {
console.log(result);
alert("Success");
})
.catch(() => {
alert("Error.");
});
}
handleSubmit(event) {
const {
match: { params }
} = this.props;
if (params && params.pk) {
this.handleUpdate(params.pk);
} else {
this.handleCreate();
}
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="row">
<div className="form-group col-sm-8">
<label>Name:</label>
<input
className="form-control"
type="text"
ref="name"/>
</div>
</div>
<div className="row">
<AuthorsDropDown onChange={this.onChangeAuthor}/>
<PublishersDropDown onChange={this.onChangePublisher}/>
</div>
<div className="row">
<div className="form-group col-sm-4">
<label>Pages:</label>
<input
className="form-control"
type="number"
ref="pages"/>
</div>
<div className="form-group col-sm-4">
<label>ISBN:</label>
<input
className="form-control"
type="text"
ref="inventor_number"/>
</div>
</div>
<div className="row">
<div className="form-group col-sm-4">
<label>Info:</label>
<textarea
className="form-control"
ref="description"/>
</div>
</div>
<input className="btn btn-primary" type="submit" value="ok"/>
</form>
);
}
}
export default BookCreateUpdate;
I think you should consider a different way of tackling this problem. If I understand your requirement this component both creates and updates books. In this case, the <BookCreateUpdate/>
component should receive a property which is the target book. For creation, it should be an empty object. For an update, it should be the object to update.
I think the mentioned concern relates to when editing. I suppose that books are persisted somewhere. If a book is passed in edit mode then the initial value should be passed down to the child components (input, AuthorsDropDown, PublishersDropDown) from the parent (<BookCreateUpdate/>
).
class BookCreateUpdate extends Component {
constructor(props) {
super(props);
this.state(this.props.book)
}
onInputChange = propName => (e) => {
this.setState({[propName]: e.target.value })
}
...
handleCreate() {
const bookDraft = this.state;
bookService
.createBook(bookDraft)
.then(result => {
alert("The book is added!");
})
.catch(() => {
alert("Error!!");
});
}
...
render(){
const bookDraft = this.state;
return (
...
<div className="row">
<div className="form-group col-sm-8">
<label>Name:</label>
<input
className="form-control"
type="text"
value = {bookDraft.name}
onChange={this.onInputChange('name')}
/>
</div>
</div>
<AuthorsDropDown onChange={this.onChangeAuthor} authorId = {bookDraft.authorId}/>
<PublishersDropDown onChange={this.onChangePublisher} publisherId = {bookDraft.publisherId}/>
....
)
}
}
BookCreateUpdate.propsTypes = {
book: PropTypes.object
}
BookCreateUpdate.defaultProp = {
book: {authorId: null, publisherId: null}
}
It is also best not to use refs in this case. It is cleaner to pass a value to input and pass a callback for onChange event.