Skip to content
esr360 edited this page Feb 16, 2020 · 5 revisions

The state parameter is used to provide both the state and props of the desired element. To access an Component's state, you should pass the state as a prop to the Component.

const styles = {
  myComponent: ({ state }) => ({
    ...(state.active && {
      // ...some styles
    }),
    ...(state.foo && {
      // ...some styles
    })
  })
}

const MyModule = (props) => {
  const [isActive, setActive] = useState(false);

  return (
    <Module styles={styles} onClick={() => setActive(!isActive)}>
      <Component name='myComponent' active={isActive} foo={props.alpha}>
        ...
      </Component>
    </Module>
  );
}
<MyModule alpha />

If your styles object instead exists as a function, you can style the parent <Module> based off its own props as well:

const styles = ({ state }) => {{
  ...(state.alpha && {
    // ...some styles
  }),

  myComponent: ({ state }) => ({
    ...
  })
}}
<MyModule alpha />

Sass Equivalent

This concept is very similar to using the ampersand (&) in Sass, the difference is that instead of the state coming from class names, it comes from actual React state:

.myModule {
  &.alpha {
    // ...some styles
  }

  .myComponent {
    &.active {
      // ...some styles
    }
    &.foo {
      // ...some styles
    }
  }
}
<div class="myModule alpha">
  <div class="myComponent active foo">
    ...
  </div>
</div>

You can avoid using functions to access state by using keywords in your styles object that correspond to Cell Query Expressions. The above initial example can be re-written as:

Prepend the state's/prop's name with is-

const styles = {
  myComponent: {
    'is-active': {
      // ...some styles
    },
    'is-foo': {
      // ...some styles
    }
  }
}

This is useful for configuration, and using configuration to store cosmetic sylistic properties.

Accessing Parent's State

You can access the state/props of the parent element from a Component by using $-is-:

const styles = {
  myComponent: {
    '$-is-foo': {
      // ...some styles
    }
  }
}

const MyModule = (props) => (
  <Module styles={styles} {...props}>
    <Component name='myComponent'>{props.children}</Component>
  </Module>
);
<MyModule foo />

Learn how to use this concept in conjunction with context keywords

Clone this wiki locally