0

I have a series of commonly named properties, and I'd like to have the un-common part of the name used in other places. I know that wording is a little convoluted, but perhaps an example will help. What I want is something like:

const MyComponent = ({lgProp, xlProp, mdProp, smProp, defaultProp}) => {
    let current = defaultProp;
    let myString = 'foo';

    ['sm', 'md', 'lg', 'xl'].forEach(size => {
        const newValue = // somehow get the value of the property ${size}Prop
        if (current !== newValue) {
            myString += ` ${size}: ${newValue}`;
            current = newValue;
        }
    });
}

The canonical answer to this type of question seems to be here, but all of the answers there either refer to dynamically referencing keys in objects, or dynamically referencing variables in pure JS in the Window or this scope. I can't seem to make any of them work for referencing property names.

There are also several sections on dynamically creating property names for components, but that's the wrong direction for me.

Things I've tried:

newValue = `${size}Prop`;         // string
newValue = [`${size}Prop`];       // string
newValue = [${size} + 'Prop'];    // string
newValue = this[${size} + 'Prop'] // TypeError

I mean, there are only so many props, so I could just write a bunch of if statements, but that seems so inelegant. Is there an attractive/elegant way to variably reference the prop names?

philolegein
  • 1,099
  • 10
  • 28

0 Answers0