0

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.

2 Answers 2

2

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>
   )}
Sign up to request clarification or add additional context in comments.

1 Comment

I was stupid and put "function" before the function, which VSCode told me doesn't work. But with the ()=> I don't even need a function anymore. Thank you!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.