Change element color with React

Asked

Viewed 3,091 times

1

I am trying to change the color of an element based on the status string.

Ex.: Green to 'Active', Red to 'Inactive', Gray to 'Blocked'

I managed to do this in JS Puro, but I’m having trouble making this change with React.

Current code in React:

import React, { Component } from "react";
import { Link } from 'react-router-dom'
import './users.css'
import axios from 'axios'

const apiUrl = 'http://localhost:3001/data'

const initialState = {
    user: {name: '', email: '', tel: '', status: ''},
    list: []
}

export default class Users extends Component {

    state = { ...initialState}

    UNSAFE_componentWillMount() {
        axios(apiUrl).then(resp => {
            this.setState({ list: resp.data })
        })
    }

    load(user) {
        this.setState({ user }) 
    }

    remove(user) {
        axios.delete(`${apiUrl}/${user.id}`).then(resp => {
            const list = this.state.list.filter( u => u !== user)
            this.setState({ list })
        })
    }

    statusColor(user) {

    }

    renderList() {
        return this.state.list.map(user => {
            return (            
            <div className="row align-items-center w-100 divCustom" key={user.id}>
                <div className="col-lg-3">
                    <div className="col">{user.name}</div>
                    <div className="col">{user.contact.email}</div>
                </div>
                    <div className="col-lg-3">
                        <div className="col">{user.contact.tel}</div>
                    </div>
                <div className="col-lg-3 d-flex justify-content-start">
                    <div className="status-custom"></div>
                    <div className="col text-custom">{user.status}</div>
                </div>
                <div className="col-lg-3">
                    <button type="button" className="btnCustom float-r mr-2">Editar</button>
                </div>
            </div>
        )}
    )


    }

    render() {

        return (
        <div>
            <div className="row">
                <div className="col-md-10">
                    <h5>Listagem de Clientes</h5>
                </div>
                <div className="col-md-2 mt-2">
                    <Link to="/register"><button type="button" className="btnNvCliente">Novo cliente</button></Link>
                </div>
            </div>
            {this.renderList()}
      </div>
        )
    }
}

Pure JS code (this one worked):

class Bd {
  constructor(){
    let id = localStorage.getItem('id')
    if (id === null) {
      localStorage.setItem('id', 0)
    }
}
  getProximoId() {
    let proximoId = localStorage.getItem('id')
    return parseInt(proximoId) + 1
  }
  gravar(d) {   
    let id = this.getProximoId()
    localStorage.setItem(id, JSON.stringify(d))
    localStorage.setItem('id', id)
  }
  recuperarClientes() {

    let clientes = Array()

    let id_ = localStorage.getItem('id')

    for (let i = 1; i <= id_; i++){
      let cliente = JSON.parse(localStorage.getItem(i))

      if (cliente === null) {
        continue
      }
      cliente.id_ = i
      clientes.push(cliente)
    }
    return clientes
  }

}

let bd = new Bd()

function listaCliente(clientes = Array(), filter = false) {
  if(clientes.length == 0 && filter == false) {
    clientes = bd.recuperarClientes()
  }

  let listaCliente = document.getElementById('listaClientes')


  clientes.forEach(function(d) {

    switch (d.status) {
      case '1': d.status = 'Ativo'
        break
      case '2': d.status = 'Inativo'
        break
      case '3': d.status = 'Bloqueado'
        break
    }

console.log(d)
    $('#listaClientes').append(`
    <div class="row align-items-center w-100 divCustom">
        <div class="col-lg-3">
          <div class="col">${d.name}</div>
          <div class="col">${d.contact.email}</div>
        </div>
        <div class="col-lg-3">
          <div class="col" style=>${d.cpf}</div>
          <div class="col" style=>${d.contact.tel}</div>
        </div>
        <div class="col-lg-3 d-flex justify-content-start">
          <div class="statusCustom"></div>
          <div class="col textoCustom">${d.status}</div>
        </div>
        <div class="col-lg-3">
           <button type="button" class="btnCustom float-r mr-3">Editar</button>
        </div>
      </div>

  `);

  let status = document.getElementsByClassName('statusCustom');
  let statusColor = document.getElementsByClassName('textoCustom');
    for(i=0; i<statusColor.length; i++) {
      let statusTexto = statusColor[i].textContent.trim();
      switch(statusTexto) {
          case 'Ativo':
          status[i].style.backgroundColor = '#49AD5B';
          break
          case 'Inativo':
          status[i].style.backgroundColor = '#D6323F';
          break
          case 'Bloqueado':
          status[i].style.backgroundColor = '#D2A710';
          break
      }
    }

  })
}

1 answer

3


You can add classes using {}, for example:

className={user.status}

It is possible to concatenate with strings as well:

className={'class-name-as-string' + user.status}
// ou
className={`class-name-as-string ${user.status}`}

From this class you can customize via css

.ativo { background-color: green }
.inativo { background-color: red }
.bloqueado { background-color: gray }
  • I thought about doing it that way, but if you have a status with two words you cannot create the class in . css

  • 1

    can do user.status.split(' ').join('-') to exchange the " " for "-"

Browser other questions tagged

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