2

I can't access the value of event.target.value from a React child Component, but I can from an HTML tag.

In the example given: it doesn't work for the Button tag (React Component) but works for the button tag (html tag).


import React from "react";
import Button from "./components/Button";

class Calculator extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            topText: "0"
        }
        this.handleClick = this.handleClick.bind(this);

    }

        handleClick(event) {
            this.setState({ topText: event.target.value })
        }

    render() {
        return (
            <div>
                <div>{this.state.topText}</div>
                <Button value='1' onClick={this.handleClick}/>
                <button value="2" onClick={this.handleClick}>2</button>
            </div>
        )
}
}

export default Calculator

1
  • 2
    can you provide the code for ./components/Button? Commented Jun 25, 2019 at 22:32

3 Answers 3

1

You cannot have onClick on components. They have to be on DOM elements (Eg. div, button, etc).

Here, Button is a component. The solution will be to pass in onClick as a prop and attach it to the element in Button component.

function Button(props) {
  return <button onClick={props.onClick}>Click Me</button>;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Do you have onClick handled inside your button component ? If no thats the reason.

As you are passing onClick props on Button component, So inside Button component.

<button  onClick={onClick}/>

At the end onClick should be on HTML component only inside Button.

Comments

0

This is because onClick is passed as a prop for the button component. As long as you handle the prop inside the component you should be fine.

This should be inside your button component.

render () {
    return <button  onClick={this.props.onClick}/>2</button>;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.