0

I'm having trouble getting onClick working in reactJS. I put together this fiddle and am sure its something trivial. Code is below, see fildle for (not)working example:

var Bar=React.createClass({
    render: function() {
    return (
    <div className="bar" style={{width: this.props.width+"px"}}>                {this.props.width}</div>)
  }
})

var ClickableBar=React.createClass({

    clickBar: function(e) {
        alert('clicked');
        this.setState({width:220});
    },
    render: function() {
      return (
      <Bar onClick={this.clickBar} width={this.state.width}/>
      )
  }
})

ReactDOM.render(
  <ClickableBar width="20"/>,
  document.getElementById('container')
);

3 Answers 3

1

You just need to pass the handler through as a prop:

var Bar = React.createClass({
    render: function() {
    return (
      <div onClick={this.props.onClick} className="bar" style={{width: this.props.width+"px"}}>{this.props.width}</div>
    );
  }
});

Otherwise, your div will be created without a click listener on it, since a "Bar" doesn't really exist in the dom (only the div is actually there).

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

Comments

0

And you also missed to initialize your state

getInitialState: function(){
  return {
    width: 30
  }
}

Otherwise you will get an error

Uncaught TypeError: Cannot read property 'width' of null

I prefer using style in this way

render(){
  var myStyle = {width: 200, backgroundColor: green};
  return <div style={myStyle }> ... </div>
}

It also works with React. Fiddle example

Thanks

Comments

0

You just need to bind the function with the DOM element.

<Bar onClick={this.clickBar.bind(this)} width={this.state.width}/>

or

<Bar onClick={() => {this.clickBar()}} width={this.state.width}/>

If you want to call function by passing the event:

<select onClick = {(event) => {self.funcName(event)}} >

If you want to call function by passing arguments:

 <select onClick = {(event) => {self.funcName(event, arg1)}} >

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.