React onClick on stateless component

Viewed 2817

I have been trying to fire an onClick on a react component. The event fires if I use

<button onClick={()=>this.goToPage('next')}>Next Page</button>

If I use the same method on a stateless component, it doesn't fire:

<PageButton onClick={()=>this.goToPage('next')}>Next Page</PageButton>

Why this is not possible?

2 Answers

Because what you are defining is a custom component. Note, that everything that you provide to the custom component is considered as props. So, your onClick method is also provided as props. Essentially you'll be required to do -

<PageButton onClick={()=>this.goToPage('next')}>Next Page</PageButton>

and in your <PageButton /> component -

<button onClick={this.props.onClick}>Next Page</button>

if you know what props you are providing to this component and not providing any unnecessary props, you can even spread the props object, like -

<button {...this.props}>Next Page</button>

Note - If you have other props to provide to this component as well, kindly refrain from using this method, as this will result in many unrecognized function warnings.

PS: Even if you write

<PageButton style={{backgroundColor: 'red}}>Next Page</PageButton>

it won't work because, this is treated as a prop. You'll need to handle the style prop in the render method of this <PageButton/> component

This does not work on a stateless component because the onClick is considered as a prop rather a event listener , you should implement. For example inside PageButton you should implement something like this

render(){ return <div onClick={()=>this.props.onClick('next')}/> }

Related