Search code examples
javascriptreactjsstyled-components

How to use string to find object key?


How can I select an object key in a theme object using a string used in react component prop?

theme

{
  palette: {
    primary: {
      main: '#dc2626',
      dark: '#7f1d1d',
      light: '#fecaca',
    }
    text: '#111827',
  }
}

component

const Typography = ({ color, children }) => (
  <p style={{ color: theme.palette[color] }}>{children}</p>
);

How I want to use the component:

<Typography color='primary.main'>Hello world</Typography>

Let me know if this is a bad practice and should be avoided anyway.

I tried to use the eval function but found out it was not secure and considered to be a bad practice.


Solution

  • If you are just looking how to get a nested field in an object, you should look at lodash's get function.

    Example :

    export default const theme = {
      palette: {
        primary: {
          main: '#dc2626',
          dark: '#7f1d1d',
          light: '#fecaca',
        }
        text: '#111827',
      }
    };
    

    Component

    import { get } from lodash library;
    import theme from './theme.js';
    
    export default function MyComponent({ children }) {
      const nestedFieldPath = 'palette.primary.main';
    
      // Get nested field value
      const nestedFieldValue = get(theme, nestedFieldPath);
    
      return <p color={nestedFieldValue}>{children}</p>
    }