0

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 : &nbsp;&nbsp; <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.

1
  • Not sure if this is what you want/need but you could create a state to hold the input values and then populate it using onChange. From there you can reference your state in addBook e.g name : this.state.name Commented Nov 1, 2019 at 6:48

1 Answer 1

2

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!!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.