onClick by Innerhtml React?

Asked

Viewed 248 times

1

I’m trying to create a img with the Event of onClick in the React but it’s printing the code that way on the Web.

inserir a descrição da imagem aqui

My Internet code is like this:

 coluna4.innerHTML = `<img onClick={() => this.apagar(${key})} class='ml-6'  width='30' height='30' src='https://cdn.icon-icons.com/icons2/1489/PNG/128/rubbishbin_102620.png' alt='Excluir' title='Excluir' />`

My function that receives parameter:

apagar = (key) => {
    console.log(key)

}

Example Complete Code

export default class Product extends Component {
    state = {
        produtos: [],

    }

    componentDidMount() {

        for (var i = 0; i < sessionStorage.length; i++) {
            var key = sessionStorage.key(i)
            var session = sessionStorage.getItem(key);
            var split = session.split('-');
            var tabela = document.getElementById('tb-cart');
            var linha = tabela.insertRow(-1);
            //Adiciona dua coluna na linha criada <td></td> <td></td>
            var coluna1 = linha.insertCell(0);
            var coluna2 = linha.insertCell(1);
            var coluna3 = linha.insertCell(2);
            var coluna4 = linha.insertCell(3);
            //Inclui o valor do campo do formulário em sua respectiva coluna
            coluna1.innerHTML = split[1];
            coluna2.innerHTML = split[0];
            coluna3.innerHTML = split[2];
            coluna4.innerHTML = `<img onClick={() => this.apagar(${key})} class='ml-6'  width='30' height='30' src='https://cdn.icon-icons.com/icons2/1489/PNG/128/rubbishbin_102620.png' alt='Excluir' title='Excluir' />`
        }
    }

    inserirCarrinho = async (id) => {
        const response = await api.get(`/livros/listar/${id}`)
        sessionStorage.setItem(id, response.data.descricao + "-" + response.data.nome + "-" + response.data.valor)
    }

    apagar =  (key) => {
        console.log(key)

    }

    render() {
        return (
            <div>
                <Header />
                <Table id="tb-cart" className="container" striped bordered hover>
                    <thead class="thead-dark">
                        <tr>
                            <th>Nome livro</th>
                            <th>Descrição</th>
                            <th>Valor</th>
                            <th></th>
                        </tr>
                    </thead>
                </Table>

            </div >
        )
    }
}
  • coluna4.innerHTML already have wrong commands right away if you realize that you must ta starting, has to be done with the commands of the React, I’d like to help, but since I don’t know all your code gets complicated.

  • I’ll comment on my code

  • You know that part where you have the method componentDidMount() if you have to do this with command of the React, needs to learn the right way ... understood the problem?

  • 1

    Not yet expensive, componentDidMount() is not from React?

  • I decided to make an example ... just test is how it fills a table and any element because the React needs to control the states of this component.

1 answer

1


You are using React in the wrong way, and there does not have the expected result that is a simple assembly of a table, let’s go to an example to understand what should do:

class Product extends React.Component {
  state = {
    produtos: [],
  }
  componentDidMount() {
      const items = [
        {
          nome: 'nome 1',
          descricao: 'descricao 1',
          valor: 125.55
        },
        {
          nome: 'nome 2',
          descricao: 'descricao 2',
          valor: 200.55
        }
      ];
      this.setState({produtos: items});
  }
  apagar = key => {
    console.log(key);
  }
  render() {
    const { produtos } = this.state;
    return ( 
      <div> 
        <table className="table">
          <tr>
            <th>Nome Livro</th>
            <th>Descrição</th>
            <th>Valor</th>
            <th></th>
          </tr>       
          { produtos.map((p, i) => (
            <tr key={i}>
              <td>{p.nome}</td>
              <td>{p.descricao}</td>
              <td>{p.valor}</td>
              <td><img onClick={() => this.apagar(i)} class='ml-6'  width='30' height='30' src='https://cdn.icon-icons.com/icons2/1489/PNG/128/rubbishbin_102620.png' alt='Excluir' title='Excluir' 
 style={{cursor:'pointer'}}/></td>
            </tr>
          ))}
        </table>
      </div>
    )
  }
}

ReactDOM.render( < Product / > , document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>

  • I had done so at first, but when I was going to insert another product it overwritten the old.

  • @Gustavohenrique so it depends on how you are doing, if you realized there the correct way to make the component renders the information, then follow this logic. How are you doing the insert? if the answer served you with solution please accept as the answer to your question...

Browser other questions tagged

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