skip to Main Content

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()}

2

Answers


  1. Chosen as BEST ANSWER

    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,
    }
    

  2. You can combine the styles via rest operator to combine two objects with styles in one in prop style.

    style={{...mystyle, ...containerStyle}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search