I have a React component
export default class Archive extends React.Component { ... } componentDidMount and onClick methods partially use the same code, except for slight change in parameters.
Is it possible to create a function inside the component class so it can be reused in the scope of the component?
We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree. Example: Program to demonstrate the creation of functional components.
1. Setup. First, create a new folder called, “CustomComponents,” then open your terminal and use the npx create-react-app command to create a quickly create a new React project called “custom-components.”
It is possible, but it is not a good solution at all. Yeah, it creates new function on each re-render, but it's not a case if you don't pass them as props.
You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:
export default class Archive extends React.Component { saySomething(something) { console.log(something); } handleClick(e) { this.saySomething("element clicked"); } componentDidMount() { this.saySomething("component did mount"); } render() { return <button onClick={this.handleClick.bind(this)} value="Click me" />; } }
Another way:
export default class Archive extends React.Component { saySomething = (something) => { console.log(something); } handleClick = (e) => { this.saySomething("element clicked"); } componentDidMount() { this.saySomething("component did mount"); } render() { return <button onClick={this.handleClick} value="Click me" />; } } In this format you don't need to use bind
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