Embedding SVG into ReactJS

后端 未结 6 1228
春和景丽
春和景丽 2020-11-28 03:20

Is is possible to embed SVG markup into a ReactJS component?

render: function() {
  return (
    
      

        
6条回答
  •  伪装坚强ぢ
    2020-11-28 04:09

    Update 2016-05-27

    As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (classclassName, style="color: purple"style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with , , and inline styles:

    function SvgWithXlink (props) {
        return (
            
                
                
                    
                        
                    
                
    
                black
                
                { props.fill }
                
                blue
                
            
        );
    }
    

    Working codepen demo

    For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.


    Previous answer

    You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

            render: function() {
                return (
                    
                        
                    
                );
            }
    

    At which point you can think about adding props like fill, or whatever else might be useful to configure.

提交回复
热议问题