Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hydrate tag attributes #61

Open
stla opened this issue May 22, 2021 · 2 comments
Open

hydrate tag attributes #61

stla opened this issue May 22, 2021 · 2 comments

Comments

@stla
Copy link
Contributor

stla commented May 22, 2021

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
Copy link
Contributor Author

stla commented May 25, 2021

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

@timelyportfolio
Copy link
Collaborator

These are great @stla. Thanks for sharing these.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants