Why I can't pass value to the stateless component as a props?

Hello
I’m working on my calculator project (React)

bellow is part of my code from sandbox
My question is such
At this moment I have Display Button and App components
from App components I’m passing: label, value and onClick event and id
but when I’m trying to change App state ={result: “0”} in the handleChange
only id changing state I have try value or label and only id could change state
What is wrong with my attempt and why I cant setStatte correctly with value or label? strong text

import React from "react";

const Display = props => {
  return (
    <div className="App">
      <h3>{props.result}</h3>
    </div>
  );
};

const Button = props => {
  // console.log(typeof props.label);
  return (
    <div className="App">
      <h5
        label={props.label}
        className="btn"
        value={props.value}
        id={props.id}
        onClick={props.onClick}
      >
        {props.label}
      </h5>
    </div>
  );
};

class App extends React.Component {
  state = {
    result: "0"
  };

  handleCalculate = event => {
    event.preventDefault();
    console.log(event.target.label);
    this.setState({
      result: event.target.value
    });
  };

  render() {
    return (
      <div>
        <Display id="display" result={this.state.result} />
        <Button value="1" label="1" onClick={this.handleCalculate} id="one" />
        <Button value="2" label="2" onClick={this.handleCalculate} id="two" />
        <Button value="3" label="3" onClick={this.handleCalculate} id="three" />
        <Button value="4" label="4" onClick={this.handleCalculate} id="four" />
        <Button value="5" label="5" onClick={this.handleCalculate} id="five" />
        <Button value="6" label="6" onClick={this.handleCalculate} id="six" />
      </div>
    );
  }
}

export default App;

Probably because headings (h1…h6 tags) don’t have attributes label and value.

2 Likes

You’re absolutely right, from what I’m reading. Here’s from React’s own docs:

In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it.

taken from https://reactjs.org/blog/2017/09/08/dom-attributes-in-react-16.html

2 Likes

So, as a workaround, use custom attributes. :wink:

Thanks for advise :slight_smile:

Actually React will pass down those unknown attributes, but they won’t appear on the event.
Here’s an example: https://codesandbox.io/s/81lqnml1k9 (you can inspect element to see attributes).

1 Like