user944513
user944513

Reputation: 12729

how to get input value on button click in stateless component?

could you please tell me how to get input value on button click in stateless component .I want to pass input value in container component I tried like this .here is my code https://codesandbox.io/s/l9j42k5q49

import React from "react";
import PropTypes from "prop-types";

const TabbarComponent = props => {
  const onInputChange = event => {};
  return (
    <div>
      <input type="text" />
      <button onClick={() => props.addEventHandler()}>Add Items</button>
    </div>
  );
};

TabbarComponent.propTypes = {
  addEventHandler: PropTypes.func
};

export default TabbarComponent;

here I want input value in this function

addButtonClickHandler(val) {
    alert("ddd");
    let names = this.state.names.slice();
    names.push(val);
    this.setState({
      names: names
    });
  }

val is input field value whatever user enter in input field

Upvotes: 0

Views: 1077

Answers (1)

Chris
Chris

Reputation: 59531

You don't need to give onClick a fat arrow function. Just give it the reference to the addButtonClickHandler, like this:

<button onClick={props.addEventHandler}>Add Items</button>

You can do a fat arrow function if you want (not recommended), but in that case you need to pass the event too:

<button onClick={(e) => props.addEventHandler(e)}>Add Items</button>

Upvotes: 2

Related Questions