Henok Tesfaye
Henok Tesfaye

Reputation: 9560

Passing same props to child elements at once

Since the original source code is too big. I can't post it, let me give you another short example.

Parent (ES6 class component)

render(){
    const { sortKey, isactive } = this.state;
    return (
        <Sort cKey={sortKey} title="A" name="Title" />
        <Sort cKey={sortKey} title="B" name="Author" />
        <Sort cKey={sortKey} title="C" name="Comment" />
        <Sort cKey={sortKey} title="D" name="Point" />
    )
}

For simplicity i wrote only 4 Sort components. As you can see all Sort components have the same cKey property. Does React have simple way to pass this property to all Sort components at once?

Upvotes: 1

Views: 51

Answers (2)

Estus Flask
Estus Flask

Reputation: 222494

A map of titles and names is actually needed:

titleNameMap = new Map([
  ['A', 'Title'],
  ...
]);
// or since `Map`-specific features aren't in use, `Map` could be skipped:
titleNameMap = [
  ['A', 'Title'],
  ...
];

render(){
    const { sortKey, isactive } = this.state;
    return (
        [...titleNameMap].map(([title, name]) => <Sort cKey={sortKey} title={title} name={name} />);
    )
}

As you can see all Sort components have the same cKey property. Does React have simple way pass this property to all Sort components at once?

React is minimalistic and unopinionated, it doesn't address such cases. A recommended approach is to use higher-order components (HOC):

const withSortKey = (WrappedComponent, sortKey) => props => (
  <WrappedComponent cKey={sortKey} {...props} />
));

...
render(){
    const { sortKey, isactive } = this.state;
    const KeyedSort = withSortKey(Sort, sortKey);
    return (
        [...titleNameMap].map(([title, name]) => <KeyedSort title={title} name={name} />);
    )
}
...

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281686

Instead of rendering the Sort components separately, you can simply render them using a map like

return (
    [{title: 'A', name: "Title"}, { title: 'B',  name: "Author"}, {title: 'C', name: "Comment"},{ title: 'D',  name: "Point"}].map((obj) => {
         return <Sort key={obj.title} cKey={sortKey} title={obj.title} name={obj.name}/>
    })

)

Upvotes: 1

Related Questions