Skip to content Skip to sidebar Skip to footer

React/ Eslint - Jsx Props Should Not Use Arrow Functions

I'm currently creating a component in react and i'm using the ES Lint rule react/jsx-no-bind. My issue here is that I want to be able to pass a parameter to my components function.

Solution 1:

You can refactor button into its own component:

classMyButtonextendsComponent {
  static propTypes = {
    language: PropTypes.string.isRequired,
  };

  onClick = () =>console.log(this.props.language);

  render() {
    const {language} = this.props;
    return (
      <buttononClick={this.onClick}type="submit">
        {language}
      </button>);
  }
}

and then in your LanguageDropDown class, use MyButton like this:

classLanguageDropdownextendsComponent {
  ...

  render() {
    return (
      <div>
        {this.props.languages.map(lang => <MyButtonkey={lang}language={lang}/>)}
      </div>
    )
  }

  ...
}

A couple of additional things:

  • You have a typo onCLick should be onClick
  • You need a key for repeated items

Solution 2:

try the below code. here I tried by taking the value into the state, same can be tried using props. class LanguageDropdown extends Component { constructor(props) { super(props); this.state = {languages:['telugu','hindi','english']}; // this.changeLanguage = this.changeLanguage.bind(this); }

changeLanguage(event,lang){
    //event.preventDefault();console.log('change lang: '+JSON.stringify(lang));
  };

  render() {
    return (
      <div>
        {this.state.languages.map(lang => <buttononClick={(event)=>this.changeLanguage(event,lang)}>{lang}</button>)}
      </div>
    )
  }
}


render(<LanguageDropdown />, document.getElementById('root'));

when you bind the handler in the onClick event where you are passing the value to the handler, then we have to pass that value from the event and collect it to get that value.

Post a Comment for "React/ Eslint - Jsx Props Should Not Use Arrow Functions"