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;
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.
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.
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.
/* 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With