Reputation: 606
I want to give user an interface where the props are independent of capitalization. For example:
<MyComponent prop1="value1" Prop2="value2" />
<MyComponent ProP1="value1" prop2="value2" />
both should be valid and work the same way. While I want to avoid modifying the original props, as the props may contain a large set of data, I am planning to avoid cloning them as well. Is there a good way I can achieve this?
Upvotes: 0
Views: 80
Reputation: 1074335
I wouldn't recommend doing that, but that wasn't your question. Your question was whether you can. :-D Yes, you can, via destructuring with default values. For instance:
const MyComponent = ({Prop1, prop1 = Prop1, Prop2, prop2 = Prop2}) => {
// Use `prop1` and `prop2` here
};
or as a function declaration:
function MyComponent({Prop1, prop1 = Prop1, Prop2, prop2 = Prop2}) {
// Use `prop1` and `prop2` here
}
or in the render
of a class component:
render() {
const {Prop1, prop1 = Prop1, Prop2, prop2 = Prop2} = this.props;
// Use `prop1` and `prop2` here
}
The parameter destructuring {Prop1, prop1 = Prop1, Prop2, prop2 = Prop2}
says:
Prop1
(will be undefined
if not provided)prop1
(will be undefined
if not provided) and default it to the value of Prop1
if it's not provided/is undefined
Prop2
/prop2
)Here's an example (just using a plain function, since this is about destructuring):
function example({Prop1, prop1 = Prop1, Prop2, prop2 = Prop2}) {
console.log(`prop1 = "${prop1}"`);
console.log(`prop2 = "${prop2}"`);
}
example({Prop1: "a1", prop2: "b1"});
example({prop1: "a2", Prop2: "b2"});
(I've been known to use this to work around the class
vs. className
silliness: {"class": cls, className = cls}
then use className
in the code.)
Alternatively, since props is an object, you could convert all the prop names to lower case:
const {prop1, prop2} = Object.fromEntries(
Object.entries(props).map(([name, value]) => [name.toLowerCase(), value])
);
Upvotes: 2
Reputation: 1591
Try something like this:
const inpProps = {};
Object.keys(props).forEach((key) => {
inpProps[key.toLowerCase()]= props[key];
});
Upvotes: 1