Kirk Ross
Kirk Ross

Reputation: 7153

clickHandler in stateless component?

I am a React noobie and I'm trying to create a simple (reusable) history back button using a stateless component but I'm not sure how to incorporate / where to put a clickHandler. Do I need to use a stateful component? This is my non-working approximation of 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;

Upvotes: 7

Views: 5077

Answers (1)

azium
azium

Reputation: 20614

You're writing object / class like code outside of an object or class. Just think of this code like normal JavaScript:

import React from 'react';

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

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

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

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

However, in this situation it's very common to pass functions down from a parent who may be interacting with state for instance.

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

Also you're saying "in a const" but you can use let or var if you want, or even export it directly.

Upvotes: 11

Related Questions