ads-icons-react
Version:
ADS icons for React usage
44 lines (35 loc) • 1.78 kB
JavaScript
const { createComponentName, convertPxToRem } = require("../utils/tools");
/**
* Generates a React component template string from an icon object containing the file name and SVG data.
* The function parses the SVG data to inject dynamic properties such as width, height (based on the file name),
* and fill color. It constructs a React component with these dynamic properties and returns the component as a string.
*
* @param {Object} icon - An object containing the 'file' name and SVG 'data' of an icon.
* @param {string} icon.file - The file name of the icon, used to derive the component name and size.
* @param {string} icon.data - The raw SVG data of the icon.
* @returns {string|null} A string containing the React component template, or null if the SVG content is invalid.
*/
const reactIconComponent = ({ file, data }) => {
const size = file.replace(".svg", "").split("_").pop();
const parsedData = data.replace(
"<svg",
`<svg aria-hidden="true" width={size} height={size} {...rest} fill={fill}`
);
const parsedName = createComponentName(file);
return `import React, { FC } from 'react';
import { ADSIcon } from "../../icons.types";
const ${parsedName}: FC<ADSIcon> =
({fill, size = '${convertPxToRem(
size
)}', ...rest}) => (${parsedData})
export default ${parsedName}`;
};
/**
* Wraps the `reactIconComponent` function to directly return a React component template string
* for a given icon object.
*
* @param {Object} icon - An object containing the 'file' name and SVG 'data' of an icon.
* @returns {string|null} A string containing the React component template, or null if the SVG content is invalid.
*/
const templateReact = (icon) => `${reactIconComponent(icon, icon.data)}`;
module.exports = templateReact;