I want to call a method inside another method like this, but it is never called.
Button:
<span onClick={this.firstMethod()}>Click me</span>
Component:
class App extends Component {
constructor(props) {
super(props);
this.state = {..};
}
firstMethod = () => (event) => {
console.log("button clicked")
this.secondMethod();
}
secondMethod = () => (event) => {
console.log("this is never called!")
}
render() {..}
}
The first method is called, but not the second one. I tried to add to the constructor
this.secondMethod = this.secondMethod.bind(this);
which is recommended in all the other solutions but nothing seems to work for me. How can I call the second method correctly?
There are two problems here.
First one: You are defining your functions wrong.
firstMethod = () => (event) => {
console.log("button clicked")
this.secondMethod();
}
Like this, you are returning another function from your function. So, it should be:
firstMethod = ( event ) => {
console.log("button clicked")
this.secondMethod();
}
Second: You are not using onClick handler, instead invoking the function immediately.
<span onClick={this.firstMethod()}>Click me</span>
So, this should be:
<span onClick={() => this.firstMethod()}>Click me</span>
If you use the first version, yours, when component renders first time your function runs immediately, but click does not work. onClick needs a handler.
Here, I totally agree #Danko's comment. You should use this onClick with the function reference.
<span onClick={this.firstMethod}>Click me</span>
With this method, your function is not recreated every time your component renders since it uses your handler function with its reference. Also, no struggle writing the handler manually.
Lastly, if you define your functions as an arrow one, you don't need to .bind them.
Here is the working code.
class App extends React.Component {
firstMethod = () => {
console.log("button clicked")
this.secondMethod();
}
secondMethod = () =>
console.log("this is never called!")
// or maybe even better not using an arrow function for the
// second method since it is already bound to `this` since we
// invoke it from the firstMethod. For details, look the comments please.
/* secondMethod() {
console.log("this is never called!")
} */
render() {
return(
<span onClick={this.firstMethod}>Click me</span>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Instead of firstMethod = () => (event) try firstMethod = (event) => and instead of secondMethod = () => (event) => { try secondMethod = (event) => {
The bad news is that you can't bind arrow functions because they're lexically bound. See:
Can you bind arrow functions?
The good news is that "lexical binding" means that they should already have App as their this, i.e. it should would without explicitly binding. You'd likely redefining them as undefined, or some other odd thing by treating them this way in the constructor.
Try this, it works for me.
firstMethod = () => {
console.log("click handler for button is provided")
return (event) => this.secondMethod(event);
}
secondMethod = (event) => {
console.log("This is being called with", event);
}
Your second method returns a new function, which is redundant.
Also, your second method can be not bound, since the first method has the context already.
secondMethod = () => (event) => { ... } should be secondMethod(evnt) { ... }
Here is the working and optimized example https://codesandbox.io/s/pkl90rqmyj
Can you check this way using this url: https://codesandbox.io/s/q4l643womw
I think you're using wrong bind methods but here you can see an example
class App extends Component {
constructor() {
super();
this.state = {
num: 1,
};
this.firstMethod = this.firstMethod.bind(this);
this.secondMethod = this.secondMethod.bind(this);
}
firstMethod() {
this.secondMethod();
}
secondMethod() {
this.setState({
num: 2
});
}
render() {
return (
<div className="App">
<button onClick={this.firstMethod}>click</button>
<label>{this.state.num}</label>
</div>
);
}
}
Related
I have problem here with this.greet() is undefined i have to bind onlick event dirrently to work, any ideas how to fix it ?
import React from 'react';
export default class Example1 extends React.Component {
constructor() {
super();
this.message = {
greeting: 'Hello',
name: 'World',
};
}
greet() {
const { greeting, name } = this.message;
console.log(`${greeting} ${name}!`);
}
onClick() {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick}>Greet the world</button>
</div>
);
}
}
i have tried many other ways but it didnt work out anyway.
You lost this reference, you have to bind your functions:
<button onClick={this.onClick.bind(this)}>Greet the world</button>
or pass an arrow function
<button onClick={() => this.onClick()}>Greet the world</button>
The reason you are getting undefined as a value for this.greet() is because the this keyword in JS references the current object and in this case it doesn't exist and so .greet() method is actually attached to the window object. The solution you used as you described with binding works because bind attached the method to the current object context. Now, if you don't want to bind methods, you can use arrow functions like so:
import React from 'react';
export default class Example1 extends React.Component {
constructor() {
super();
this.message = {
greeting: 'Hello',
name: 'World',
};
}
greet = () => {
const { greeting, name } = this.message;
console.log(`${greeting} ${name}!`);
}
onClick = () => {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick}>Greet the world</button>
</div>
);
}
}
This works because the value of this is inherited into the local scope of the methods of the component class.
if you want have "this" in your class component you should add props inside constructor invocation and also into the super
constructor(props) {
super(props);
this.greet = this.greet.bind(this) // need's to be bounded
}
Problem is this keyword.
This is because of the way this works in javascript.
this loses it's context when it gets used in callbacks.
There are two solutions for this problem. But I would recommend the arrow function solution the most.
Bind this in the onClick callback.
onClick() {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick.bind(this)}>Greet the world</button>
</div>
);
}
Use arrow functions for defining callbacks, ( personally recommended )
onClick = () => {
try {
this.greet();
} catch (e) {
console.error('Why have I failed? Can you fix me?');
}
}
render() {
return (
<div>
<button onClick={this.onClick}>Greet the world</button>
</div>
);
}
First your function signature should be descriptive and then you can call the function like this
<button onClick={this.onClick()}>Greet the world</button>
Im doing ReactJS course in Codeacademny and they confused me.
(EDIT - full code) Photo of the code :
and there's no constructor or anywhere call to any bind method for the scream class method.
However in further exercises they tell you can't do that.
I probably miss something.
Apparently this.scream is an arrow function. Arrow function does not require binding. It points to the right context by default.
scream = () => { ... }
and there's no constructor or anywhere call to any bind method for the scream class method.
You only have to bind this to the component instance when the method actually uses this internally.
That's not the case in your example, so there is no need to bind it. No matter how the method is executed, it will always produce the same output.
Here is an example without React to demonstrate the difference:
var obj = {
value: 42,
method1() { // doesn't use `this`
console.log("yey!");
},
method2() { // uses `this`
console.log(this.value);
},
};
obj.method1(); // works
obj.method2(); // works
var m1 = obj.method1;
var m2 = obj.method2;
m1(); // works
m2(); // BROKEN!
var m2bound = obj.method2.bind(obj);
m2bound(); // works
scream = () => { ... }
render() {
return <button onClick={()=>this.scream()}>AAAAAH!</button>;
}
ou have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as
onClick={this.handleClick}, you should bind that method.
When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class. For example, this Toggle component renders a button that lets the user toggle between “ON” and “OFF” states:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);```
You can simply use an arrow function (no need to bind in constructor).
scream = () => { console.log('Here') }
render() {
return <button onClick={this.scream}>AAAAAH!</button>;
}
Or you can call this function inline by.
render() {
return <button onClick={() => console.log('Here')}>AAAAAH!</button>;
}
You should use arrow functions for event handling to bind the function to the object. Other solution is to auto bind each function in the constructor like :
class Test{
constructor(){
Object.getOwnPropertyNames(Test.prototype).forEach(
method => this[method] = this[method].bind(this));
}
Read about #AutoBind decorator for more details.
I'm new to React and JavaScript.
I have a Menu component which renders an animation onClick and then redirects the app to another route, /coffee.
I would like to pass the value which was clicked (selected) to function this.gotoCoffee and update this.state.select, but I don't know how, since I am mapping all items in this.state.coffees in the same onClick event.
How do I do this and update this.state.select to the clicked value?
My code:
class Menus extends Component{
constructor (props) {
super(props);
this.state = {
coffees:[],
select: '',
isLoading: false,
redirect: false
};
};
gotoCoffee = () => {
this.setState({isLoading:true})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
}
renderCoffee = () => {
if (this.state.redirect) {
return (<Redirect to={`/coffee/${this.state.select}`} />)
}
}
render(){
const data = this.state.coffees;
return (
<div>
<h1 className="title is-1"><font color="#C86428">Menu</font></h1>
<hr/><br/>
{data.map(c =>
<span key={c}>
<div>
{this.state.isLoading && <Brewing />}
{this.renderCoffee()}
<div onClick={() => this.gotoCoffee()}
<strong><font color="#C86428">{c}</font></strong></div>
</div>
</span>)
}
</div>
);
}
}
export default withRouter(Menus);
I have tried passing the value like so:
gotoCoffee = (e) => {
this.setState({isLoading:true,select:e})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
console.log(this.state.select)
}
an like so:
<div onClick={(c) => this.gotoCoffee(c)}
or so:
<div onClick={(event => this.gotoCoffee(event.target.value}
but console.log(this.state.select) shows me 'undefined' for both tries.
It appears that I'm passing the Class with 'c'.
browser shows me precisely that on the uri at redirect:
http://localhost/coffee/[object%20Object]
Now if I pass mapped 'c' to {this.renderCoffee(c)}, which not an onClick event, I manage to pass the array items.
But I need to pass not the object, but the clicked value 'c' to this.gotoCoffee(c), and THEN update this.state.select.
How do I fix this?
You can pass index of element to gotoCoffee with closure in render. Then in gotoCoffee, just access that element as this.state.coffees[index].
gotoCoffee = (index) => {
this.setState({isLoading:true, select: this.state.coffees[index]})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
}
render(){
const data = this.state.coffees;
return (
<div>
<h1 className="title is-1"><font color="#C86428">Menu</font></h1>
<hr/><br/>
{data.map((c, index) =>
<span key={c}>
<div>
{this.state.isLoading && <Brewing />}
{this.renderCoffee()}
<div onClick={() => this.gotoCoffee(index)}
<strong><font color="#C86428">{c}</font></strong></div>
</div>
</span>)
}
</div>
);
}
}
so based off your code you could do it a couple of ways.
onClick=(event) => this.gotoCoffee(event.target.value)
This looks like the approach you want.
onClick=() => this.gotoCoffee(c)
c would be related to your item in the array.
All the answers look alright and working for you and it's obvious you made a mistake by not passing the correct value in click handler. But since you're new in this era I thought it's better to change your implementation this way:
It's not necessary use constructor at all and you can declare a state property with initial values:
class Menus extends Component{
state= {
/* state properties */
};
}
When you declare functions in render method it always creates a new one each rendering which has some cost and is not optimized. It's better if you use currying:
handleClick = selected => () => { /* handle click */ }
render () {
// ...
coffees.map( coffee =>
// ...
<div onClick={ this.handleClick(coffee) }>
// ...
}
You can redirect with history.replace since you wrapped your component with withRouterand that's helpful here cause you redirecting on click and get rid of renderCoffee method:
handleClick = selected => () =>
this.setState(
{ isLoading: true},
() => setTimeout(
() => {
const { history } = this.props;
this.setState({ isLoading: false });
history.replace(`/${coffee}`);
}
, 5000)
);
Since Redirect replaces route and I think you want normal page change not replacing I suggest using history.push instead.
You've actually almost got it in your question. I'm betting the reason your state is undefined is due to the short lived nature of event. setState is an asynchronous action and does not always occur immediately. By passing the event off directly and allowing the function to proceed as normal, the event is released before state can be set. My advice would be to update your gotoCoffee function to this:
gotoCoffee = (e) => {
const selectedCoffee = e.target.value
this.setState({isLoading:true,select:selectedCoffee},() =>
{console.log(this.state.select})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
}
Note that I moved your console.log line to a callback function within setState so that it's not triggered until AFTER state has updated. Any time you are using a class component and need to do something immediately after updating state, use the callback function.
I was expecting to see undefined being logged when the "Without binding" button was clicked because when you pass a method reference plainly as a callback, it shouldn't be called with the right this context, but with an arrow function, it should.
However, I saw that the callback function could access this and the value of this.state.number was logged properly. The method reference and arrow function performed the exact same. Why?
This does not have to do with arrow function class properties, it has to do with passing a reference to a method as a callback to setState as opposed to an arrow function.
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 1,
};
}
onClickWithThisBindingInCallback = () => {
this.setState({ number: 2 }, () => { this.myCallback(); });
};
onClickWithoutThisBindingInCallback = () => {
const myCb = this.myCallback;
this.setState({ number: 3 }, myCb);
};
myCallback() {
console.log(this.state.number);
}
render() {
return (
<div className="App">
<button onClick={this.onClickWithThisBindingInCallback}>With binding</button>
<button onClick={this.onClickWithoutThisBindingInCallback}>Without binding</button>
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://unpkg.com/react#16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.2.0/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
React calls the callback function of setState with the component's instance this, as seen by this line of code.
Credits: #Li357
It is because you are given a lambda function to it:
onClickWithThisBinding = () => {
A lambda function is executed in it's given context. So the binding is actually onClick={() => { .. }}. That is why it has the this context.
This is due to the use of the arrow function.
Arrow functions always have the same this of their surrounding code.
See more here.
If you want the method not to be bound to that specific class you can use a normal function like this.
onClickWithoutThisBinding() {
const myCb = this.myCallback;
this.setState({ number: 3 }, myCb);
};
I have a component that I have created:
class Create extends Component {
constructor(props) {
super(props);
}
render() {
var playlistDOM = this.renderPlaylists(this.props.playlists);
return (
<div>
{playlistDOM}
</div>
)
}
activatePlaylist(playlistId) {
debugger;
}
renderPlaylists(playlists) {
return playlists.map(playlist => {
return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>
});
}
}
function mapStateToProps(state) {
return {
playlists: state.playlists
}
}
export default connect(mapStateToProps)(Create);
When I render this page, activatePlaylist is called for each playlist in my map. If I bind activatePlaylist like:
activatePlaylist.bind(this, playlist.playlist_id)
I can also use an anonymous function:
onClick={() => this.activatePlaylist(playlist.playlist_id)}
then it works as expected. Why does this happen?
You need pass to onClick reference to function, when you do like this activatePlaylist( .. ) you call function and pass to onClick value that returned from activatePlaylist. You can use one of these three options:
1. using .bind
activatePlaylist.bind(this, playlist.playlist_id)
2. using arrow function
onClick={ () => this.activatePlaylist(playlist.playlist_id) }
3. or return function from activatePlaylist
activatePlaylist(playlistId) {
return function () {
// you code
}
}
I know this post is a few years old already, but just to reference the latest React tutorial/documentation about this common mistake (I made it too) from https://reactjs.org/tutorial/tutorial.html:
Note
To save typing and avoid the confusing behavior of this, we will use
the arrow function syntax for event handlers here and further below:
class Square extends React.Component {
render() {
return (
<button className="square" onClick={() => alert('click')}>
{this.props.value}
</button>
);
}
}
Notice how with onClick={() => alert('click')}, we’re passing a
function as the onClick prop. React will only call this function after
a click. Forgetting () => and writing onClick={alert('click')} is a
common mistake, and would fire the alert every time the component
re-renders.
This behaviour was documented when React announced the release of class based components.
https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html
Autobinding
React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.
Therefore we decided not to have this built-in into React's class model. You can still explicitly prebind methods in your constructor if you want.
import React from 'react';
import { Page ,Navbar, Popup} from 'framework7-react';
class AssignmentDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
}
onSelectList=(ProjectId)=>{
return(
console.log(ProjectId,"projectid")
)
}
render() {
return (
<li key={index} onClick={()=> this.onSelectList(item.ProjectId)}></li>
)}
The way you passing the method this.activatePlaylist(playlist.playlist_id), will call the method immediately. You should pass the reference of the method to the onClick event. Follow one of the below-mentioned implementation to resolve your problem.
1.
onClick={this.activatePlaylist.bind(this,playlist.playlist_id)}
Here bind property is used to create a reference of the this.activatePlaylist method by passing this context and argument playlist.playlist_id
2.
onClick={ (event) => { this.activatePlaylist.(playlist.playlist_id)}}
This will attach a function to the onClick event which will get triggered on user click action only. When this code exectues the this.activatePlaylist method will be called.