React Hook How to pass styles

Viewed 24

I wonder if there is a simpler way to pass the default style property (as it is a default property) to a custom component. I hope someone can just tell me how to improve the following code.

Given:

const MyIcon= ()=>{
  return <img src={GMNT_N_Black}/>
}

The following style property is not being applied.

<MyIcon style={{width:"1em",height:"1em"}}/>

I'd like to pass the default property style to the img element in MyIcon.

I made it work with the following code:

const MyIcon = ({style})=>{
  return <img src={imported_img} style={style}/>
}

However, I suspect there should be an easier and cleaner way to pass the style, especially since img is the only element inside. Does exist this 'simpler' way or is {style} as props the proper way in this situation?

2 Answers

You can use it like this

<MyIcon style={{width:"1em",height:"1em"}}/>

    const MyIcon = (props)=>{
      return <img src={imported_img} {...props}/>
    }

Whatever property you pass will be applied automatically

You can use type React.CSSProperties for your styles. Suggestion supported.

const MyIcon = ({ style }: { style: React.CSSProperties }) => {
  return <img src={'imported_img'} style={style} />;
};
// Or 
interface MyIconProps {
  style?: React.CSSProperties;
}
const MyIcon: React.FC<MyIconProps> = ({ style }) => {
  return <img src={'imported_img'} style={style} />;
};

enter image description here

Related