react-R / reactR

React for R

Home Page:https://react-R.github.io/reactR

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

hydrate tag attributes

stla opened this issue · comments

commented

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]);
  }
}
commented

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;
}

These are great @stla. Thanks for sharing these.