ClickHandler in a stateless component?

I am a React noobie and I am trying to create a simple (reusable) button back to back using a stateless component, but I'm not sure how to enable / where to put clickHandler. Do I need to use a component with state? This is my inoperative approach to what I'm trying to do.

import React from 'react';

const BtnBack = () => (
  <button className="btn btn-back" onClick={this.handleClick}>BACK</button>
);

handleClick() {
  // history back code
};

export default BtnBack;
+4
source share
1 answer

You write an object / class as code outside of an object or class. Think of this code as normal JavaScript:

import React from 'react';

const YourButton = () => (
  <button onClick={yourFunction}>BACK</button>
)

function yourFunction(event) {
  console.log('hello there')
}

You can also embed this function if you want to pass more arguments:

const YourButton = () => (
  <button onClick={event => yourFunction(event, 'foo', 'bar')}>BACK</button>
)

However, in this situation, it is very often to transfer functions down from the parent, which can interact with the state, for example.

const YourButton = props => (
  <button onClick={props.yourFunction}>BACK</button>
)

" const", let var, , .

+5

All Articles