1

I want to use an event handler to redirect a user to another route in reactJS but I have not figured out how i can pass down it's props to the event handler function.

<button onClick={ChallengeActions.OpenChallenge(item.title) }>Start<button>

This is what my event listener looks like

onOpenChallenge: function(url) {

    window.location.href = url;
}

The problem is that the function automatically fires up whenever i load the page instead of waiting for the event handler, I also get the following error.

Uncaught Error: Invariant Violation: Expected onClick listener to be a function, instead got type object
1

2 Answers 2

1

You need to take care of the following:

  1. event handlers need to be mapped to a function:
<button onClick={this.onChallengeButtonClicked}>Start</button>
  1. You need to tell each button to which item it corresponds to:
<button item={item} onClick={this.onChallengeButtonClicked}>Start</button>
  1. Event handler function can detect which button item was clicked by accessing the event parameter:
onChallengeButtonClicked: function(event) {
    item = event.currentTarget.item;
    window.location.href = item.title;
}
Sign up to request clarification or add additional context in comments.

Comments

0
var ChildComponent = React.createClass({
    render: function () {
        var myCustomValue = "testing this out";
        return (
            <h1 onClick={this.props.customEvent.bind(this, myCustomValue)}>Testing child click function</h1>
        )
    }
});

var ParentComponent = React.createClass({
    customEvent: function (value) {
        // do something wtih value
        alert("you passed " + value);
    },
    render: function () {
        return (
            <ChildComponent customEvent={this.customEvent} />  
        )
    }
});

React.render(
    <ParentComponent customEvent={this.customEvent} />,
    document.getElementById('example')
)

3 Comments

I understand this way, but suppose i want to pass a value to the the event how would i do it ?
i updated my answer with a full example of how you can pass values from a child to the parent during an event.
Thanks, I actually decided to use a Link instead but I am gonna need this as well. Will test and comment how it goes

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.