Assign className depending on a propp

0

I am creating a reusable component and one of its features that I want to add is that the background color can be defined with a property.

At this time, my component looks like this:

import React, {Component} from 'react'
import { Row, Col } from 'reactstrap'

class Objetivo extends Component {
  render() {
    return (
      <div className="objetivos-portada">
        <Col className={'bg-dark text-light p-3'}>
          <h4 className="text-white">{this.props.title}</h4>
        </Col>
      </div>
    )
  }
}

But the className bg-dark is fixed.

I want to call the component that way:

<Objetivo clase={'dark'} title={'Cobertura'} />
<Objetivo clase={'secondary'} title={'Aprobación'} />

And let the class change to bg-dark or bg-secondary or any color passed to it as a value in property clase .

    
asked by toledano 10.09.2018 в 02:49
source

2 answers

3

You might use template literals by defining the className property, so :

    <Col className={'bg-${this.props.clase} text-light p-3'}>
      <h4 className="text-white">{this.props.title}</h4>
    </Col>
    
answered by 11.09.2018 / 03:40
source
1

Try to handle it with the state or props , with your code and the states it would look something like this:

    import React, {Component} from 'react'
    import { Row, Col } from 'reactstrap'

    class Objetivo extends Component {

      constructor (props) {
       super(props)

       this.state = {
        clase: "bg-dark text-light p-3"
       };
     }

      render() {
        return (
          <div className="objetivos-portada">
            <Col className={this.state.clase}>
              <h4 className="text-white">{this.props.title}</h4>
            </Col>
          </div>
        )
      }
    }

or

        import React, {Component} from 'react'
        import { Row, Col } from 'reactstrap'

        class Objetivo extends Component {

          constructor (props) {
           super(props)

           this.state = {
            clase: "dark"
           };
         }

          render() {
            return (
              <div className="objetivos-portada">
                <Col className={'bg-${this.props.clase} text-light p-3'}>
                  <h4 className="text-white">{this.props.title}</h4>
                </Col>
              </div>
            )
          }
        }

When you make an event that you can update the state you place the other class, imagine you call a function that updates it as:

actualizarBg = () => {
    this.setState({
      clase: "primary"
    });
  }
    
answered by 11.09.2018 в 03:46