最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add prop dynamically to last element in an array of React components - Stack Overflow

programmeradmin1浏览0评论

This is a question I've searched everywhere with but I cannot find a resolution, as I can not edit the props object.

So this is what is being done so far. We have a menu. In this menu, we have sub sections. Currently we achieve this doing something like:

const firstSectionItems = [];
const secondSectionItems = [];
firstSectionItems.push(
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
    sectionEnd
  />
);
secondSectionItems.push(
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
    sectionEnd
  />
);

const items = [...firstSectionItems, ...secondSectionItems];

The sectionEnd prop adds a divider after the menu item to split the sections up in the menu. But what if someone added a menu item? They would have to ensure they move the sectionEnd prop. What I would like to do is add this sectionEnd to the ponent in the last element of each array. Is this possible? If so, how?

This is a question I've searched everywhere with but I cannot find a resolution, as I can not edit the props object.

So this is what is being done so far. We have a menu. In this menu, we have sub sections. Currently we achieve this doing something like:

const firstSectionItems = [];
const secondSectionItems = [];
firstSectionItems.push(
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
    sectionEnd
  />
);
secondSectionItems.push(
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
  />,
  <MenuItem
    onClick={() => {}}
    sectionEnd
  />
);

const items = [...firstSectionItems, ...secondSectionItems];

The sectionEnd prop adds a divider after the menu item to split the sections up in the menu. But what if someone added a menu item? They would have to ensure they move the sectionEnd prop. What I would like to do is add this sectionEnd to the ponent in the last element of each array. Is this possible? If so, how?

Share Improve this question asked Dec 22, 2017 at 9:38 CharlieCharlie 2763 silver badges14 bronze badges 2
  • Someone added a menu item when? In the codebase or in the run-time? – rishat Commented Dec 22, 2017 at 9:49
  • In the codebase. I'm just trying to make the code more maintainable. – Charlie Commented Dec 22, 2017 at 10:17
Add a ment  | 

5 Answers 5

Reset to default 3

In my opinion is better to use arrays then use .map and manage object (plain) in the array as description to build items:

let firstItems = [{ onclick: () => {}},{ onclick: () => {}}];

and then, in JSX:

{ firstItems.map((item, index) => (
    <MenuItem
       onClick={item.onClick}
       sectionEnd={index === firstItems.length - 1} 
   />
  ))
}

So you can change property working with a plain array of object and properties instead of instantiated JSX elements.

You can add a key to each menuitem and have an array lastItems that will contain keys of items last added in the respective sections, in the state. Then on rendering each item, you can add a divider by checking if that key is included in the lastItems.

Why not use HOC ? In that way you can, just leave your MenuItem ponent clean, so that HOC just need to know about the size of current array and the current index over the iteration, so you have something like

const WithSectionEndAtLastItem = (props ) => { const {size, index, ...menuProps} = props;
const isLastItem = size - 1 === index;
return <MenuItem {...menuProps} sectionEnd={isLastItem} \>};

So when iterating over elements do something like

const size = firstItems.length;
const currentSection = firstItems.map((props , index) => <WithSectionEndAtLastItem {...props} index={index} size{size} \>);
return currentSection;

It should do the trick.

I hope you find it useful.

I would create a menu dynamically and keep track of last element. Here is what i mean:

class List extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      items: ['I', 'like', 'SO'],
      item: '',
      last: 2
    }
    this.add = this.add.bind(this);
    this.change = this.change.bind(this);
  }
  change(e){
    this.setState({
        [e.target.name]: e.target.value
    })
  }
  add(){
    const last = this.state.items.length;
    this.setState({
        items: [...this.state.items, this.state.item],
      last,
      item: ''
    })
  }

  render(){
    return (
      <div>
        <ul>
          {this.state.items.map((item, i) =>
            <li key={item}>
              {item}
              // here you can pass props only to the last element
              // i just print it as the last element   
              {this.state.last === i ? ' - Last' : ''}
            </li>)
          }

        </ul>
        <input name="item" type="text" value={this.state.item} onChange={this.change}/>
        <button onClick={this.add}>Add new</button>
      </div>
    )
  }
}

ReactDOM.render(
  <List />,
  document.getElementById('container')
);

Worked example.

Maybe you should look at it in a more expressive way :

const firstSectionItems = [
  <MenuItem onClick={() => {}} />,
  <MenuItem onClick={() => {}} />,
  <MenuItem onClick={() => {}} />,
];
const secondSectionItems = [
  <MenuItem onClick={() => {}} />,
  <MenuItem onClick={() => {}} />,
  <MenuItem onClick={() => {}} />,
];

const items = [...firstSectionItems, <MenuDivider />, ...secondSectionItems];

Even better, you can then create a MenuSection ponent to wrap the divider behavior :

const MenuSection = ({ items }) => ([
  ...items,
  <MenuDivider />,
]);

const menu = [
  <MenuSection items={firstSectionItems} />,
  <MenuSection items={secondSectionItems} />,
];
发布评论

评论列表(0)

  1. 暂无评论