Unable To Get The Value Of Variable Inside A Function
Solution 1:
`${type}`.toUpperCase()
is the string "PADDING"
, not the variable PADDING
. You need to put the contents of those variables (PADDING
and MARGIN
) in a structure you can use to look them up by name, like an object:
const values = {
padding: [0, 1, 2, 3, 4],
margin: [0, 8, 16],
};
constgenerateStyle = (type) => {
const styles = {};
values[type].forEach((item) => {
styles[`${type}-${item}`] = {
[type]: `${item}px !important`,
};
});
return styles;
};
console.log(generateStyle('padding'));
Solution 2:
This should work:
constPADDING = [0, 1, 2, 3, 4];
constMARGIN = [0, 8, 16 ];
constgenerateStyles = (array, type) => {
if(array && array.length) {
let styles = {};
array.forEach(item => {
styles[`${type}-${item}`] = {
[type]: `${item}px !important`
}
})
return styles
}
}
console.log(generateStyles(PADDING, "padding"));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
All you need to do is pass an array of values (PADDING) and a css property name ("padding").
Hope it helps!
Solution 3:
In case if you don't want to generate a structure, you can also make use of eval and iterate over the variable.
For eg.
constPADDING = [0, 1, 2, 3, 4];
constMARGIN = [0, 8, 16 ];
constgenerateStyle = (type) => {
const styles = {};
const upperCase = type.toUpperCase();
eval(upperCase).forEach((item) => {
styles[`${type}-${item}`] = {
[type]: `${item}px !important`,
};
});
return styles;
};
generateStyle('padding');
Solution 4:
on passing 'padding' to generateStyle, you are just passing a string not the array. so to pass array you need to pass as PADDING only.
Solution 5:
Because variable PADDING
is an array, but when you set the string 'padding' parameter for function generateStyle
the foreach will iterate over string 'padding', but as I know you can't iterate over string with Array.forEach()
Post a Comment for "Unable To Get The Value Of Variable Inside A Function"