Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clickHandler in stateless component?

Tags:

reactjs

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;
like image 743
Kirk Ross Avatar asked Jun 09 '16 22:06

Kirk Ross


People also ask

Can stateless components have functions?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

How is stateless component different from a stateful component?

Stateful and Stateless Components In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components.

What are the advantages of stateless components in React JS?

The answer is performance. Stateless functional components can be rendered faster. One of the reasons why this is the case is because stateless functional components do not require some of the life cycle hooks.

How do you call a component on a click button?

/* Write a button component */ import React from 'react'; const Button = (props) => { return ( <button>{props. text}</button> ); } export {Button}; What is this? import React from 'react'; const ListComponent = (props) => { return ( <div> <h1>{props.


1 Answers

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.

like image 99
azium Avatar answered Oct 20 '22 01:10

azium