79269510

Date: 2024-12-10 19:27:49
Score: 0.5
Natty:
Report link

Found solution.

Simple example:

   const propertyName = 'color';
   const propertyValue = 'red';
   const dynamicObject = {
     [propertyName]: propertyValue,
   };

   console.log(dynamicObject); 
   <Text style={dynamicObject}>test</Text>

More complex:

  const properties: string[] = ['color', 'fontSize', 'padding'];
  const values: (string | number)[] = ['red', 35, 10];

  const dynamicStyle: { [key: string]: string | number } = properties.reduce((style, property: string, index: number) => {
    style[property] = values[index];
    return style;
  }, {} as { [key: string]: string | number });

  console.log(dynamicStyle); 
  <Text style={dynamicStyle}>test</Text>

So key is that inside [ ] can be property name.

styles: Record<string, string | number> = {};

and now can add as many key-value pairs as needed.

styles[propName] = value;

Thank you!

Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Vakhtangi Abashidze