Skip to content

Instantly share code, notes, and snippets.

@ufocoder
Last active June 13, 2024 21:03
Show Gist options
  • Save ufocoder/4e378083f08b635afacdaa92cc5fb866 to your computer and use it in GitHub Desktop.
Save ufocoder/4e378083f08b635afacdaa92cc5fb866 to your computer and use it in GitHub Desktop.
myStyled.jsx
import React from "react";
const toCamelCase = (str) => {
const words = str.split("-");
for (let i = 1; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
}
return words.join('');
};
const convertToStyleObject = (str) => {
const style = {};
const properties = str.split(";")
properties.forEach(property => {
const [name, value] = property.split(":");
if (!value) {
return;
}
const propertyName = name.trim();
const propertyValue = value.trim();
if (!propertyName || !propertyValue) {
return
};
style[toCamelCase(propertyName)] = propertyValue;
});
return style;
};
const createStyle = (props, rawStyles, interpolations) => rawStyles.reduce((acc, rawStyle, i) => {
const value = interpolations[i] instanceof Function ? interpolations[i](props) : interpolations[i];
return `${acc}${rawStyle}${value || ''}`;
}, '');
const myStyled = (tagName) => (rawStyles, ...interpolations) => {
return (props) => {
const { children, ...otherProps } = props;
const style = convertToStyleObject(createStyle(otherProps, rawStyles, interpolations));
return React.createElement(tagName, {...otherProps, style }, children);
}
}
myStyled.div = myStyled('div');
myStyled.button = myStyled('button');
export default myStyled;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment