jmunsch
jmunsch

Reputation: 24089

React svg xmlns:xlink identifier expected

How do I fix the identifier expected error when using typescript, react, and svgs?

return (
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" 
                   xmlns:xlink="http://www.w3.org/1999/xlink" >
         <defs> ... </defs>
         <use ... xlink:href="#path-1"/>
    </svg>
);

Upvotes: 29

Views: 34756

Answers (3)

Brad Vanderbush
Brad Vanderbush

Reputation: 169

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


import convert from 'convert-svg-react'
 
function App(props) {
    
    const svg = convert(`<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-caret-right-square-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
    <path fill-rule="evenodd" d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm5.5 10a.5.5 0 0 0 .832.374l4.5-4a.5.5 0 0 0 0-.748l-4.5-4A.5.5 0 0 0 5.5 4v8z"/>
    </svg>`);
 
    return (
        <>      
            {/* Will display your converted code for copying as well as your svg */}
            {svg}
        </>
    );
}
 
ReactDOM.render(
    <App />,
    document.getElementById('app')
);

Upvotes: 0

Nico Diz
Nico Diz

Reputation: 1504

You can also use the svg-inline-react dependency and pass the original SVG as a string. And you do not have to worry about translating HTML to JSX syntax.

    import InlineSVG from 'svg-inline-react';

    const svgSource = `<svg xmlns="......</svg>`;
    <InlineSVG src={svgSource} />

Upvotes: 0

jmunsch
jmunsch

Reputation: 24089

Use the react specific spelling (JSX) for each attribute, for example:

return (
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" 
                   xmlnsXlink="http://www.w3.org/1999/xlink" >
         <defs> ... </defs>
         <use ... xlinkHref="#path-1"/>
    </svg>
);
  • xmlnsXlink
  • xlinkHref

also see:

Upvotes: 73

Related Questions