3

In my current project, I'm setting up mobile support the following way:

1) I'm creating all the relevant components both for desktop and mobile. On most of my pages, they're the same.

2) I'm creating two .scss files, one for desktop and one for mobile (determined by a media query covering the entire file)

3) I'm then attaching both styles in the className of my components, and then only the relevant file gets set. It looks like this:

// Styles
import styles from '../../components/Timeline/timeline.scss';
import mobileStyles from '../../components/Timeline/mobileTimeline.scss';

// Example component
<Row className={`${styles.container} ${mobileStyles.container}`}>
   <div className={`${styles.myComponent} ${mobileStyles.myComponent}`}/>
</Row>

It works great, but in order to make the code a bit cleaner, I decided to write a helper function to generate the entire string for the className ->

const setStyle = styleName => `${styles.styleName} ${mobileStyles.styleName}`

However, setStyle always returns 'unidentified' (*the function is defined after the styles imports of-course)

I think I understand why it happens, but I wonder, is there a way we could dynamically access style object properties like that?

Thanks in advance!

1 Answer 1

4

To get a property from an object given the key name in a variable, use the bracket notation:

const setStyle = styleName => `${styles[styleName]} ${mobileStyles[styleName]}`

This assumes that styles and mobileStyles are available in the scope of the function, otherwise you would also need to pass them:

const setStyle = (styleName, styles, mobileStyles) => `${styles[styleName]} ${mobileStyles[styleName]}`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.