reactR icon indicating copy to clipboard operation
reactR copied to clipboard

hydrate tag attributes

Open stla opened this issue 4 years ago • 2 comments

Hello,

There exist some React components which accept React components as props. The hydrate function does not handle this situation. So one could add this code at the beginning of the hydrate function:

for(attrib in tag.attribs){
  if(isTag(tag.attribs[attrib]){
    tag.attribs[attrib] = hydrate(components, tag.attribs[attrib]);
  }
}

stla avatar May 22 '21 23:05 stla

There are other points to deal with.

style attribute

The style attribute in a React component must be an object, not a string, with property names in camel case. I've found these function on the web to convert a string style to an object style:

const formatStringToCamelCase = str => {
  const splitted = str.split("-");
  if (splitted.length === 1) return splitted[0];
  return (
    splitted[0] +
    splitted
      .slice(1)
      .map(word => word[0].toUpperCase() + word.slice(1))
      .join("")
  );
};

const getStyleObjectFromString = str => {
  const style = {};
  str.split(";").forEach(el => {
    const [property, value] = el.split(":");
    if (!property) return;
    const formattedProperty = formatStringToCamelCase(property.trim());
    style[formattedProperty] = value.trim();
  });
  return style;
};

Usage in hydrate:

if(typeof tag.attribs.style === "string"){
  tag.attribs.style = getStyleObjectFromString(tag.attribs.style);
}

class attribute

In React, the class attribute is className.

if(tag.attribs.hasOwnProperty("class")){
  tag.attribs.className = tag.attribs.class;
  delete tag.attribs.class;
}

for attribute

The for attribute in React is htmlFor.

if(tag.attribs.hasOwnProperty("for")){
  tag.attribs.htmlFor = tag.attribs.for;
  delete tag.attribs.for;
}

stla avatar May 25 '21 08:05 stla

These are great @stla. Thanks for sharing these.

timelyportfolio avatar May 31 '21 12:05 timelyportfolio