简体   繁体   中英

Add prop dynamically to last element in an array of React components

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 component in the last element of each array. Is this possible? If so, how?

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 component 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 component to wrap the divider behavior :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM