I’m recreating an existing HTML button component that uses the <svg> element and an icon sprite sheet for icons.
I want to be able to create the <svg> element if an iconString prop has a value, and then add it to the button’s content.
I am having difficulty "building" this <svg> element within a variable, eg:
if (iconString && label) {
buttonContent = <svg className="btn-icon"><use xlink:href="/svgs/icons.svg#' + iconString + '"></use></svg> + label;
}
I can’t find or figure out the correct way to use <svg> and <use> elements along with the iconString and label props.
Would anyone be able to point me in the right direction?
My full code is:
export const button = ({ type, size, iconString, label, ...props }) => {
let buttonContent = '';
if (iconString && label) {
buttonContent = <svg className="btn-icon"><use xlink:href="/svgs/icons.svg#' + iconString + '"></use></svg> + label;
}
else {
buttonContent = label;
}
return (
<button
type="button"
className={['btn', `btn-${size}`, `btn-${type}`].join(' ')}
{...props}
>
{buttonContent}
</button>
);
};
>Solution :
It looks like you’re on the right track, but there’s a syntax issue in how you’re trying to construct the SVG element and its element. In JSX, you need to use curly braces {} to embed JavaScript expressions. Also, you should use the xlinkHref attribute instead of xlink:href for the element’s xlink reference. Here’s the corrected version of your code:
export const Button = ({ type, size, iconString, label, ...props }) => {
let buttonContent = '';
if (iconString && label) {
buttonContent = (
<>
<svg className="btn-icon">
<use xlinkHref={`/svgs/icons.svg#${iconString}`} />
</svg>
{label}
</>
);
} else {
buttonContent = label;
}
return (
<button
type="button"
className={['btn', `btn-${size}`, `btn-${type}`].join(' ')}
{...props}
>
{buttonContent}
</button>
);
};
Changes made to your code:
The component name is capitalized (Button) according to the convention for React components.
The SVG structure is enclosed in a JSX fragment (<>…</>) to allow multiple elements to be returned.
The xlinkHref attribute is used to define the SVG sprite reference.
With these changes, your code should correctly generate the SVG icon along with the label for your button component when both iconString and label props are provided.