Home > Blockchain >  Add custom CSS class via variable to returned jsx
Add custom CSS class via variable to returned jsx

Time:11-04

I've created a custom component which essentially returns html markup in order to display content based on the values passed to the component. Here's a simplified version for brevity:

interface ContainerProps {
    position?: string;
    content?: string;
    class?: string;
}

const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a", class = "" }) => {
    
    if ( position.trim().toLowerCase() === "right" ) {
        return <><div className="ion-float-right" >{content}</div><div className="clear-right"></div></>
    } else if ( position.trim().toLowerCase() === "left" ) {
        return <div className="ion-float-left">{content}</div> 
    } else {
        return null
    }
    
};

export default CardContainer;

This works great, but I now need to be able to pass a css class name to the component. However, I can't work out how to add the "class" prop to the returned html/jsx.

I tried various code such as below. However, in all cases the code was output as actual html rather than the value of the prop:

return <div className="ion-float-left"   {class}>{content}</div> 

return <div className="ion-float-left {class}" >{content}</div> 

return <div className="ion-float-left class">{content}</div> 

I also tried a few other random things in desperation and these typically cause a compilation error. What is the best way to achieve the intended result eg:

return <div className="ion-float-left myClassNameHere">{content}</div>

CodePudding user response:

its like inserting a string inside another or adding them together. You can use classname={"yourclasse" theDynamicClass} or className={yourClass ${dynamicClass}} (inbetween ``)

CodePudding user response:

return <div className=` ion-float-left ${class}``>{content}

  • Related