Collin Barrett
Collin Barrett

Reputation: 2569

Pass interfaced object as props without explicitly specifying each property value

This seems so basic that I guarantee it has been asked before... But, I can't find it. ReactJS noob here; be nice.

Is there a way to pass an interfaced object as the props to a child component without re-assigning each property in the interface?

In the example below, <MyChildComponent props={foo}/> obviously does not work because MyChildComponent expects props: IFoo.

interface IFoo {
    PropA: string;
    PropB: string;
}

export default class MyComponent extends React.Component<IFoo[], any> {
    constructor(props: IFoo[]) {
        super(props);
    }

    render() {
        return {this.props.map((foo: IFoo) => <MyChildComponent props={foo}/>)};
    }
}

export default class MyChildComponent extends React.Component<IFoo, any> {
    constructor(props: IFoo) {
        ...
    }
    ...
}

I could do something like below, but I'd prefer not to specify each property of the object as an explicit prop.

...
render() {
    return {this.props.map((foo: IFoo) => <MyChildComponent PropA={foo.PropA} PropB={foo.PropB}/>)};
}
...

Upvotes: 0

Views: 39

Answers (1)

izb
izb

Reputation: 582

<MyChildComponent {...foo} />

Upvotes: 1

Related Questions