I am passing multiple function={this.function}
as singular props from the parent component to its child components. I don't get any errors or issues with this, but I'm wondering if there's a better / cleaner way to code it.
To illustrate, here is a sample code (the parent component):
import React, { Component } from 'react';
export default class App extends Component {
function1 = () => {
// Does something
};
function2 = () => {
// Does something
};
function3 = () => {
// Does something
};
function4 = () => {
// Does something
};
function5 = () => {
// Does something
};
render() {
return (
<div>
Parent Component
<ChildComponent
function1={this.function1}
function2={this.function2}
function3={this.function3}
function4={this.function4}
function5={this.function5} />
</div>
);
}
}
It's really just a matter of code becoming a bit long. I'm wondering if there's a short way to pass functions 1 through 5, perhaps in a single line.
Thanks in advance!
Sure, there are at least two options:
import React, { Component } from 'react';
export default class App extends Component {
functions = {
function1: () => {
// Does something
},
function2: () => {
// Does something
},
function3: () => {
// Does something
},
function4: () => {
// Does something
},
function5: () => {
// Does something
}
}
render() {
return (
<div>
Parent Component
<ChildComponent functions={this.functions} />
OR
<ChildComponent {...this.functions} />
</div>
);
}
}