Im trying to convert one of my components to a functional stateless component (FSC).
But FSC will not be optimized if using ...rest
, therefore i need to destruct the components props.
I call Link as
<Link to={link} data-navbar-click="close-menu">{name}</Link>
then in Link i want to destruct the hyphen cased> data-navbar-click prop:
function Link({ to, className, onClick, target, rel, key, data-navbar-click}) {
However that doesnt compile. So i tried:
function Link({ to, className, onClick, target, rel, key, ['data-navbar-click']}) {
But that doesnt work as well.
Parents and Children Children can not pass props up to the parent. This is the one way data flow of React. It will always pass props down the component hierarchy unless your use a separate state manager like Redux.
Simplest solution: use alias.
const Link = ({
to,
className,
onClick,
target,
rel,
key,
'data-navbar-click': dataNavbarClick,
}) => {
const test = dataNavbarClick;
};
dataNavbarClick should have the value "close-menu"
You can write a utility function that transforms camelCase
key names to kebab/hyphen-case properties, picked them out out of the props object and, by using JSX spread, render them in the component.
Example below:
import kebabCase from 'lodash/kebabCase';
const props = {
dataNavAttr: 'close-menu',
itemCount: 100
}
const pickAndTransformDataProps = (props, findByKey) => {
const pickedProps = {};
Object.keys(props).map(key => {
if (key.includes(findByKey)){
pickedProps[kebabCase(key)] = props[key];
}
});
return pickedProps;
}
const pickedDataProps = pickAndTransformDataProps(props, 'data');
console.log({ pickedDataProps });
// Using JSX spread: <Component onClick={props.onClick} { ...pickedDataProps } />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With