Reputation: 69
I'm trying to send text from the input text type to another component using params. But I got the next error
TypeError: Cannot read property 'setState' of undefined
I think using redirect is the best option to do it but I'm not sure.
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {redirect: false , value: ''};
}
setRedirect(event) {
this.setState({
redirect: true,
value: event.target.value
});
};
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to={{
pathname: `/pokemon/filtered/${this.state.value}`,
}}/>;
}
};
render() {
return (
<form>
<input type="text" value={this.state.value} onChange={this.setRedirect()} />
</form>
);
}
}
Upvotes: 0
Views: 44
Reputation: 131
The correct way of binding an event handler in react is
<button onclick={activateLasers}>
In javascript world. this
is set to the caller by default. See Function.prototype.bind
on MDN.
To bind the class method to the class, you can 1. use public class fields syntax. 2. bind in the constructor.
References:
Upvotes: 0
Reputation: 218
you have to mistakes here
onChange
you actually calling the function beacuse you added '()' <input type="text" value={this.state.value} onChange={this.setRedirect} />
second becuase this is a class you need to bind the function to that class on the constructor
constructor(props) {
super(props);
this.state = {redirect: false , value: ''};
this.setRedirect = this.bind.setRedirect(this)
}
or to simplify things use arrow function because arrow function will always belongs to the object that called that function
Upvotes: 1