2

New in React, looking for a good way to build a set of nested components given a nested props object.

Take the following basic props example:

const props = [{
  label: 'Foods',
  children: [
    { label: 'Chicken', children: [] },
    { label: 'Pasta', children: [] }
  ]
}];

I would like to use this to build a nested menu:

<Item>
  <Label>Foods</Label>
  <Item><Label>Chicken</Label></Item>
  <Item><Label>Pasta</Label></Item>
</Item>

While this is a simple example, the nesting would go much deeper.

I have searched around for this, and all I am finding are pre-built components. I'm not looking for magic yet, I'm trying to understand how things work before I use other components.

What is the best way to generate a React component to efficiently render this?

2 Answers 2

3

You can have a component render itself. Here's a pure component example that should work:

const Item = ({label, children}) => (
  <div>
    <label>{label}</label>
    {children.map(child => (
      <Item label={child.label} children={child.children} />
    ))}
  </div>
);
Sign up to request clarification or add additional context in comments.

Comments

0

Just adding to Austin's answer, it could be iterative to have as many children as needed.

var Container = React.createClass({
    render: function () {
        var Items = [];
        var level = 1;
        var self = this;

        var addItem= function (filter, level) {
            filter.forEach((f)=> {

                Items.push(<Item key={f.Id} data={f} level={level} />)

                if (f.Children !== undefined && f.Children.length != 0) {
                    addFiler(f.Children, level + 1);
                }
            });
            level -= 1;
        };

        addItem(this.props.options, level);

        return (<div>{Items}</div>);
    }
});

var Item= React.createClass({
    displayName: 'filter',
    onClick: function (e) {
        this.props.onChange(this.props.data.Id);
    },

    render: function () {
        return (<div>
                <label>
                    {this.props.data.Title}
                </label>
       </div>);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.