0

I want to create custom style object through a function, something like this

function myFunc(styleParam, value){
const style = {styleParam: value} as React.CSSProperties 
return style
}

Is there a way to pass a react style parameter as a variable?

Edit: solved!

  • `const style = {[styleParam]: value} as React.CSSProperties;` (plus type annotations of course; I'd probably try to make it a generic function so you could avoid the type assertion). – T.J. Crowder Dec 08 '22 at 11:20
  • Side note: Functions that you aren't going to use with `new` or as components shouldn't start with a capital letter. While you *can* do it, it'll be confusing to other people reading your code. Non-constructor functions should start with a lower-case letter. – T.J. Crowder Dec 08 '22 at 11:20
  • Actually, it doesn't even have to be generic: `function myFunc(styleParam: keyof CSSProperties, value: CSSProperties[typeof styleParam]) { const style = {[styleParam]: value}; return style; }` https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgYQMqoApQmAprYXAZzgF84AzbEOAIilwEMBjGWgbgChOKBXAO1bAI-OCACeAMQHMAFERjiANrgyMojEAC44Aa1ziIFFOiw58MQkQA0cAG6MlvXDrSZseAsQDaivEbgFZVV1TQBdAEpETjhYuGYRBUDFFTgAXkRvIJU1DRAwnQcnXFIuOLgGGF4oUWzcLlJuBP4kgA90sSkZWVoEpWhaW1oAI2LaCK5mpPEOiWlBHuHoABN8AHVgZZgAC0G4ACYAFgmgA – T.J. Crowder Dec 08 '22 at 11:23
  • 1
    Thank you very much for solving my problem! – Никита Штанг Dec 08 '22 at 11:29

0 Answers0