Question about class integration in React Javascript components

Asked

Viewed 28 times

1

I’m having difficulty interacting a class with a component using React. To create a constructor, where the new "classe" would be inserted into my React Dom component.

Simple example below: there is the button, and just for study I would like to make the onclick of that button activate the new constructor, creating arrays with the push thus:

class List {
  constructor() {
    this.data = [];
  }

  add(data) {
    this.data.push(data);
    console.log(this.data);
  }
}

class TodoList extends List {}

const minhaLista = new TodoList();

document.getElementByClassName("**inserirtodo**").onclick = () => minhaLista.add("novo todo");

However I am using React and I am not yet familiar with the integration of classes I create with the components of Reactdom.

i would like to insert an event with the above code features on the button. For the button to generate an array written "new whole" inside the "date" object"

import React, {Component} from 'react';
import api from "../../services/api"


export default class Main extends Component {
    componentDidMount() {
        this.loadProducts();
    }

    loadProducts = () => {

    };


    render () {
        return <div>
            <button type="button" className="**inserirtodo**">
                click
            </button>
        </div>
    }
}
  • I don’t quite understand, you want to do the same from above only in React ?

1 answer

2


I created a little example:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class List {
  constructor() {
    this.data = [];
  }

  add(data) {
    this.data.push(data);
    console.log(this.data);
  }
}

class TodoList extends List {}
const minhaLista = new TodoList();

function App() {
  return (
    <div className="App">
      <div className="todo-button" onClick={() => {
        minhaLista.add("novo todo");
      }}/>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Where todo-button has the style:

.todo-button {
  width: 300px;
  height: 100px;
  background: red;
}

When clicking on the red button, a "new whole" string is added in data of minhaLista normally. This is perfectly possible / normal ("Integrate classes"). No matter the component event, you can interact with instance methods normally, modify objects normally.

You can test the example here: https://codesandbox.io/embed/heuristic-agnesi-6xfrc (Check the console)

Browser other questions tagged

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