Reputation: 29720
I have the following in my React component
export default function BookAdderComponent(props) {
const booksPresenter = new BooksRepository();
return (
<>
<h5>Add Book</h5>
name : <input></input><br/>
title : <input></input><br/>
<button onClick={() => {
booksRepo.addBook({
id: 131,
name: "My Book", //.1 how do I bind to name input?
ownerId: "[email protected]",
author: "tom hurst" //.2 how do I bind to title input?
})
}}>
add book
</button>
</>
);
}
How do I 2-way-bind my two html input values to things I am going to send in my repository function later on?
I'm looking for the simplest easiest way I need to demo this to someone.
Upvotes: 0
Views: 99
Reputation: 11257
In the example below I have added name
and title
of book to state and passed that data down to booksRepo
addBook
method on button click titled Add Book
Below is the working code:
index.js
import React from "react";
import ReactDOM from "react-dom";
import booksRepo from "./booksRepo";
class App extends React.Component {
state = {
name: "",
title: ""
};
handleClick = e => {
e.preventDefault();
booksRepo.addBook(this.state);
};
render() {
return (
<div className="App">
<h5>Add Book</h5>
<label>Name:</label>
<input
type="text"
value={this.state.name}
onChange={e => {
this.setState({ name: e.target.value });
}}
/>
<br />
<br />
<label>title:</label>
<input
type="text"
value={this.state.title}
onChange={e => {
this.setState({ title: e.target.value });
}}
/>
<br />
<br />
<button onClick={this.handleClick}>Add Book</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
booksRepo.js
const addBook = ({ name, title }) => {
console.log("the name of books is ", name);
console.log("the title of books is ", title);
};
const booksRepo = {
addBook: addBook
};
export default booksRepo;
Hope that helps!!!
Upvotes: 2