Last active
June 13, 2024 21:03
-
-
Save ufocoder/4e378083f08b635afacdaa92cc5fb866 to your computer and use it in GitHub Desktop.
myStyled.jsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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