Reputation: 3877
Please I would need a little bit of help here as I'm stuck. I'm new to react, and I'm creating a component that gets a list of available languages from the backend and display them into a dropdown, then, once the user selects a language, the component should be updated to display the selected one.
The problem I'm facing is that I don't know why, but the handleClick method is being executed three times(I have three available languages), either when the page is loaded, or when I select a new language. As a result, no matter what language I select, the last language in the list is always displayed as selected.
Please if you can have a quick look and tell me if you see something that can lead to this strange behaviour I would appreciate very much as this thing is driving me crazy.
Below the code:
import React from 'react';
class LocaleSwitcher extends React.Component {
constructor() {
super();
this.render = this.render.bind(this);
this.handleClick = this.handleClick.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
this.state = {languages: [],selectedLocale:'En'};
//This is only printed once
console.log('constructor called');
}
handleClick(locale) {
this.state.selectedLocale=locale;
// This is printed three times,
// whenever I select a locale or when the page is loaded,why?????
console.log('Selected Locale:' + locale);
}
render() {
var component = this;
component.selectedLanguage = this.props.defaultLanguage;
return (<li>{this.state.selectedLocale}
<ul className="dropdown">
{
this.state.languages.map(function (result, i) {
var url = "data/translations?locale=" + result.text;
return (<li key={i}><a onClick={component.handleClick(result.text)} href="#">{result.text}</a>
</li>);
})
}
</ul>
</li>);
}
componentDidMount() {
var component = this;
$.get('data/languages', function (result) {
component.setState({languages: result});
});
}
};
export class LocaleCurrencySwitcher extends React.Component {
render() {
return (<ul className="switchers">
<LocaleSwitcher defaultLanguage="En"/>
</ul>);
}
};
Upvotes: 1
Views: 54
Reputation: 7179
The problem is you are actually calling the handleClick
method instead of assigning the function as a callback to the onClick
attribute. You should remove the paratheses from the method and instead pass the text as a param.
onClick={component.handleClick.bind(null, result.text)}
In your case the handleClick
method is being called instead of being used as a callback.
Upvotes: 1