button event in React.JS

Asked

Viewed 32 times

-2

i want to add the chart to the panel when I click the access button, as I make it appear inside the panel I stylized without putting it right there, only after clicking the accessos button???

import React, { useEffect, useState } from 'react';
import { Bar } from 'react-chartjs-2'

import { Container, Graficos, Gerar } from './styles'

// Components
import SectionTopBar from '../../components/SectionTopBar'
import NavigationBar from '../../components/NavigationBar'

const Dashboard = () => {

  const access = () => {
    //MANDAR ADICIONAR A FUNÇÃO CHART() AQUI
  }

  const [charData, setCharData] = useState({})

  const chart = () => {
    setCharData({
      labels: ['Jorge', 'Lucas', 'Ana', 'Antonio', 'Luiza', 'Matheus', 'Luana'],
      datasets: [
        {
          label: 'Acessos',
          data: [25, 30, 13, 9, 47, 10, 21],
          backgroundColor: [
            'rgba(6, 196, 131, 0.4)'
          ],
          borderColor: [
            'rgba(6, 196, 131, 1)'
          ],
          borderWidth: 1
        }
      ]
    })
  }

  useEffect(() => {
    chart()
  }, [])

  return (
      <Container>
        <Graficos>

          <Gerar>
            <button className="card" onClick={access} >
              <div className="content-info">
                <text className="textbtn" >Acessos</text>
                <text className="quantidade" >12.000</text>
              </div>
              <div><i class="fas fa-sign-in-alt"></i></div>
            </button>

              <a></a>
            </button>
          </Gerar>

          <div className="grafico-container" >
             //ADICIONAR AQUI NO PAINEL
            <div className="painel" ><Bar data={charData} /></div>
          </div>

        </Graficos>
      </Container>
  );
}

1 answer

0

In this case the ideal would be a conditional rendering. When a variable in your program is true, render the graph.

We can do this with the hook useState react.

const Dashboard = () => {
  // Variáveis que vão armazenar o estado da página (Se o gráfico deverá ser mostrado ou não)
  const [displayChart, setDisplayChart] = useState(false);

  // Função para mostrar o gráfico ao clicar no botão
  const showChart = () => setDisplayChart(true);

  const chartData = {
    labels: ["Jorge", "Lucas", "Ana", "Antonio", "Luiza", "Matheus", "Luana"],
    datasets: [
      {
        label: "Acessos",
        data: [25, 30, 13, 9, 47, 10, 21],
        backgroundColor: ["rgba(6, 196, 131, 0.4)"],
        borderColor: ["rgba(6, 196, 131, 1)"],
        borderWidth: 1,
      },
    ],
  };

  return (
    <div>
      ... Conteúdo da página
      <button onClick={showChart}>Acessos</button>
      {/* Renderização condicional - Se a variável displayChart for "true" o gráfico será renderizado */}
      {displayChart && <Bar data={chartData} />}
    </div>
  );
};

Browser other questions tagged

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