Wonka
Wonka

Reputation: 8674

React - Render children in matching sort order?

Given a component that renders its children, I can't get the children to render sorted as per their newOrder order:

export default class EnhancedLinks extends React.Component {
  render() {
    return (
      <div>
        {React.Children.map(
          this.props.children.filter((c) => c),
          (el) => el
        )}
      </div>
    );
  }
}

export default class App extends React.Component {
  render() {
    const newOrder = ["dandelion", "cantaloupe", "apple", "banana"];

    return (
      <div>
        <EnhancedLinks>
          <div name="apple" color="red">apple</div>
          <div name="banana" color="yellow">banana</div>
          <div name="cantaloupe" color="orange">cantaloupe</div>
          <div name="dandelion" color="green">dandelion</div>
        </EnhancedLinks>
      </div>
    );
  }
}

Any idea how to get the EnhancedLinks children to render as per the order of the newOrder array?

Here's a fiddle: https://codesandbox.io/s/react-and-scss-forked-z1p0b?file=/src/index.js

Upvotes: 0

Views: 515

Answers (2)

Caitlin Willmot
Caitlin Willmot

Reputation: 31

Your EnchancedLinks component should render the div, color and text, not the outside wrapping component. This way there's less copy/pasted code and you can set the order in your array, or manipulate your array as you need to.

export default class EnhancedLinks extends React.Component {
  render() {
    return (
      <div name={this.props.name} color={this.props.color}>
        {this.props.name}
      </div>
    );
  }
}

export default class App extends React.Component {
  render() {
    const newOrder = [
      {
        name: "dandelion",
        color: "green"
      },
      {
        name: "cantaloupe",
        color: "orange"
      },
      {
        name: "apple",
        color: "red"
      },
      {
        name: "banana",
        color: "yellow"
      }];

    return (
      <div>
        {newOrder.map((link) => {
          return <EnhancedLinks {...link} />
        })}
      </div>
    );
  }
}

I've forked your fiddle with a solution I've come up with: https://codesandbox.io/s/react-and-scss-forked-c1r1f

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

Map the newOrder array to <div>s instead of writing them out individually?

    const colors = ['red', 'yellow', 'orange', 'green'];
    return (
      <div>
      <EnhancedLinks>
        {newOrder.map((name, i) => <div name={name} color={colors[i]}>{name}</div>)}
      </EnhancedLinks>
      </div>
    );

The

Upvotes: 1

Related Questions