Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destruct `data-*` (hyphen cased) attributes from props?

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.

like image 386
user3711421 Avatar asked Aug 08 '17 11:08

user3711421


People also ask

When using props do you pass data up or down to components?

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.


2 Answers

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"

like image 159
horymury Avatar answered Oct 24 '22 11:10

horymury


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 } />
like image 36
Denialos Avatar answered Oct 24 '22 11:10

Denialos