OfficialCRUGG
OfficialCRUGG

Reputation: 61

Define Functions for OnClick in React Component with ES6 Syntax

I currently structure my React Components the following:

export default class Heading extends Component {
    render() {
      return (
        <h1 onClick={changeLanguage("en_US")}>I am a Heading!</h1>
      );
    }
}

And now after some research I haven't found any way to define functions inside the Component Class that can be used inside the onClick attribute of something. Everything I found was only for React.createClass or something like that.

Upvotes: 0

Views: 93

Answers (2)

Doug Moses
Doug Moses

Reputation: 176

You should be able to define the method inside of your component. You will need to wrap your event handler so you can pass an argument to it

export default class Heading extends Component {

   changeLanguage(lang){
   }

   render() {
      return (
         <h1 onClick={()=>this.changeLanguage("en_US")}>I am a Heading!</h1>
   )}

Upvotes: 2

schoenbl
schoenbl

Reputation: 723

If the function is outside the render, you would refer to it like so:

export default class Heading extends Component {
    changeLanguage = () => {
         //do something
    }
    render() {
      return (
        <h1 onClick={()=>this.changeLanguage("en_US")}>I am a Heading!</h1>
      );
    }
}

changeLangue needs to be an arrow function to maintain context.

Upvotes: 0

Related Questions