Home > Enterprise >  How can i add a dynamic class in react?
How can i add a dynamic class in react?

Time:12-25

Here the width is mentioned inline so i want to make a card component where the width can be handled dynamically. what i mean to say is there will be one card component from which i can handle the width property dynmically through jsx suppose for one card the width is 250px and for another card the width might be 100px like this

<div className="white-box v-align ht-100" style={{ width: '250px', marginRight: '10px' }}>
                        <div className="flex-one"></div>
                        <div className="wd-80">
                            <div className="fs-xl fw-bold" style={{ color: '#142654' }}>{pct}%</div>
                            <div className="small-text">{text}</div>
                        </div>
                        </div>

CodePudding user response:

A solution to this problem might be using props:

// SomeComponent.js class
class SomeComponent {
    // Uncomment if you need to set a state
    //constructor(props) {
    //    super(props);
    //
    //    this.state = {};
    //}

    render() {
        let width = Math.min(Math.max(this.props.width, SOME_MAX_WIDTH), SOME_MIN_WIDTH); // clamp (optional)

        return ( // replace with your component
            <div style={{width: width, backgroundColor: "#23a4f6"}}>
                Width set from parent (and clamped)
            </div>
        );
    }
}
SomeComponent.defaultProps = {
    width: 200
};

// SomeComponent.js in functional
function SomeComponent({width}) {
    let width = Math.min(Math.max(this.props.width, SOME_MAX_WIDTH), SOME_MIN_WIDTH); // clamp (optional)

    return ( // replace with your component
        <div style={{width: width, backgroundColor: "#23a4f6"}}>
            Width set from parent (and clamped)
        </div>
    );
}
SomeComponent.defaultProps = {
    width: 200
};

// main.js
ReactDOM.render(<SomeComponent />, document.querySelector(".myelement"));

CodePudding user response:

You can take width variable like let width = '100px' and then apply this variable to your code like this. here width you can pass as a prop which could be any value

let width = '100px';
<div className="white-box v-align ht-100" style={{ width: width, marginRight: '10px' }}>
                        <div className="flex-one"></div>
                        <div className="wd-80">
                            <div className="fs-xl fw-bold" style={{ color: '#142654' }}>{pct}%</div>
                            <div className="small-text">{text}</div>
                        </div>
                        </div>
  • Related