Dash
Dash

Reputation: 812

Too much child component props, should i pass them using a dedicated class?

I got a Child Component which receive at least 10 props. And i'm in a situation where i have multiple Child Component (with different props).

At the moment, i have something like that

import React from 'react'
import ChildComponent from './ChildComponent';

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            childComponentDisplayed: {
                attr1: "someData",
                attr2: "someData",
                attr3: "someData",
                attr4: "someData",
                attr5: "someData",
                attr6: "someData",
                attr7: "someData"
                // etc...
            }
        }
    }

    render() {
        <ChildComponent
            attr1={this.state.childComponentDisplayed.attr1}
            attr2={this.state.childComponentDisplayed.attr2}
            attr3={this.state.childComponentDisplayed.attr3}
            attr4={this.state.childComponentDisplayed.attr4}
            attr5={this.state.childComponentDisplayed.attr5}
            attr6={this.state.childComponentDisplayed.attr6}
            attr7={this.state.childComponentDisplayed.attr7}
        ></ChildComponent>
    }
}

Is it a good practise to use a dedicated class to "simplify" this ? It would gives something like this

import React from 'react'
import ChildComponent from './ChildComponent';

class ChildComponentProps {
    constructor(attr1, attr2, attr3, attr4, attr5, attr6, attr7) {
        this.attr1 = attr1;
        this.attr2 = attr2;
        this.attr3 = attr3;
        this.attr4 = attr4;
        this.attr5 = attr5;
        this.attr6 = attr6;
        this.attr7 = attr7;
    }
}

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            childComponentDisplayed: new ChildComponent(
                "someData",
                "someData",
                "someData",
                "someData",
                "someData",
                "someData",
                "someData"
            )
        }
    }

    render() {
        <ChildComponent
            data={this.state.childComponentDisplayed}
        ></ChildComponent>
    }
}

Any advices are appreciate

Upvotes: 0

Views: 40

Answers (2)

Darkilen
Darkilen

Reputation: 571

You can use this :

<ChildComponent
    childComponentDisplayed={this.state.childComponentDisplayed}>
</ChildComponent>

And then use in <ChildComponent> the this.props.childComponentDisplayed.attrX

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

You could use the ... spread operator to simplify it e.g.

<ChildComponent {...this.state.childComponentDisplayed} />

Upvotes: 2

Related Questions