Yumi Chen
Yumi Chen

Reputation: 27

[ React.js ]Child component props not working

I'm learning React and was trying to write a program which shows the Unicode of the pressed key on screen. No error popped up but the state( pressed key and Unicode) wasn't printed on the screen, either ( the state changed accordingly well). The props were set but it's not working.

Codepen

The code(Javascript):

const key = props=>{
return (<p className="key" onTransitionEnd={props.transitionHandle}>{props.key}</p>);
    }

const charCode = props=>{
  return (<p className="charCode">{props.charCode}</p>);
}



class App extends React.Component{
  constructor(props){
    super(props);

    this.state = {key: "A", charCode: "65"}
    this.keydownHandle = this.keydownHandle.bind(this);

  document.addEventListener("keydown",function(event){
      this.keydownHandle(event);
      }.bind(this));
  }
  render(state){
    return (
      <div className="box">
        <charCode charCode={this.state.charCode}></charCode>
        <key onTransitionEnd={this.transitionHandle} key={this.state.key}></key>
      </div>
    );
  }
    keydownHandle(event){
    this.setState({
      key: String.fromCharCode(event.keyCode),
      charCode: event.keyCode
      });

  }
      transitionHandle(){ 
  document.getElementsByClassName("key").classList.remove("pressed");

  }
}

ReactDOM.render(<App/>,document.querySelector(".container"));

Thanks a lot.

Upvotes: 1

Views: 4023

Answers (1)

Karthik Ravichandran
Karthik Ravichandran

Reputation: 161

Couple of things

codepen

  1. key is one of the special attributes that cannot be passed as props (source: https://facebook.github.io/react/docs/lists-and-keys.html)

  2. User defined components must be capitalized - use Key and CharCode instead of key and charCode (source: https://facebook.github.io/react/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)

Upvotes: 1

Related Questions