How to delete an element by Key in React?

Asked

Viewed 1,964 times

0

This is the code generated, because the list is created by the routes of the pages, I would like to know a way to delete a specific Navlink, either by key or otherwise definitely, this Navlink should be deleted when the page is loaded.

<NavLink Key='0' to="/pag1" activeClassName="active" arriaCurrent="true">
<NavLink Key='1' to="/pag2" activeClassName="active" arriaCurrent="true">
<NavLink Key='2' to="/pag3" activeClassName="active" arriaCurrent="true">
<NavLink Key='3' to="/pag4" activeClassName="active" arriaCurrent="true">
<NavLink Key='4' to="/pag5" activeClassName="active" arriaCurrent="true">

This is the code for how Navlinks are generated

 <List className={classes.list}>
            {
                routes.map((prop,key) => {
                    if(prop.redirect)
                        return null;
                    return (
                        <NavLink to={prop.path}  activeClassName="active" key={key}>
                            <div className = "btnMenu">
                                <ListItem button className={classes.itemLink + (this.activeRoute(prop.path) ? " " + classes[color]:""   )}>
                                    <ListItemIcon className={classes.itemIcon + (this.activeRoute(prop.path) ? " " + classes.whiteFont:"")}>
                                        <prop.icon />
                                    </ListItemIcon>
                                    <ListItemText primary={prop.sidebarName} className={classes.itemText + (this.activeRoute(prop.path) ? " " + classes.whiteFont:"")}  disableTypography={true}/>
                                </ListItem>
                            </div>  
                        </NavLink>

                    );
                    if(key=[4]) {
                        return(
                            <teste/>
                        )
                    }
                })

            }
        </List>

2 answers

0


To remove an item when the component is rendered using the method componentDidMount

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      lista: [
        { to:"/pag0", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag1", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag2", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag3", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag4", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag5", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag6", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag7", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag8", activeClassName:"active", arriaCurrent:"true" },
        { to:"/pag9", activeClassName:"active", arriaCurrent:"true" },
      ],
    };

  }

  componentDidMount () {
    let [...lista] = this.state.lista;
    // Remove "/pag1" pelo indice
    delete lista[1];
    this.setState({
      lista: lista,
    });

    // Remove "/pag4" e "/pag9" pela propriedade "to"
    this.state.lista.forEach((item, index) => {
      (item['to'] === '/pag4' || item['to'] === '/pag9') ? delete lista[index] : null
    });
    this.setState({
      lista: lista,
    });
  }

  render() {
    return (
      <div>
        <div>
          <h4>Lista</h4>
          {this.state.lista.map((item, index) =>
            <span>{item.to}</span>
          )}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
span {
  background: #069;
  color: #fff;
  font-family: 'Verdana';
  float: left;
  margin-bottom: 5px;
  margin-right: 5px;
  padding: 0.765em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

0

It depends on how you want to delete, whether it is by onClick or by some other means...

//import React from 'react';

class Formulario extends React.Component
{
  constructor(props){
    super(props)
    this.state = {
      pessoas: [
        {name: "Juscilina"},
        {name: "Jubiscláudia"},
        {name: "Fulaninho"}
      ]
    }
  }
  //fat arrow functions não precisam de dar o .bind
  delete = (id) => {
    let pessoa = document.getElementById(id);
    pessoa.style.display = 'none';
  }

  render() {
      return (
          <div>
            {
              this.state.pessoas.map((pessoa, key) => {
                return(
                  <div key={key} id={"pessoa-"+key} onClick={() => this.delete('pessoa-'+key)}>
                    { pessoa.name }
                  </div>
                );
              })
            }
          </div>
      );
  }
}

ReactDOM.render(<Formulario/>, document.querySelector(".root"));
<div class="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Observe:

Here I’m just giving display: none ,if Voce actually wants to remove the page element could use: unmountComponentAtNode

Browser other questions tagged

You are not signed in. Login or sign up in order to post.