Search code examples
cssreactjstypescript

How do i combine styles on a div


Coming from react-native, i am trying to build a component to display data with. What i am having trouble with, is combining the styles defined within the component itself, with the ones being passed as props from outside.

In react-native this is simply achieved by putting the 2 styleobjects inside an array, but how do i do this in react?

export interface MenuItemProps {
    'containerStyle'?: React.CSSProperties,
}

export const MenuItem: React.FC<MenuItemProps> = (props) => {
const { title, selected, onClick, containerStyle } = props;

const mystyle = {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
    marginBottom: 10,
}

    return (
    <React.Fragment>
        <div
            style={[{mystyle, containerStyle}]}
            onClick={() => onClick()}

Solution

  • what i ended up doing was add the incoming containerStyle to the end of myStyle, so that incoming styling overwrites existing styling;

    const myStyle: React.CSSProperties = {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 10,
        ...containerStyle,
    }