dynamic filling of svg with data in React

Viewed 39

How I can dynamically fill data in svg? I understand that I can use map. But I don't know how to compare the id <g> with the id from the data.Or is it impossible to do this with such an implementation? What do I need to change?

const data = [
   {
    id:'el-1',
    label:'name-1',
    category:'cat-1'
   },
   {
    id:'el-2',
    label:'name-2',
    category:'cat-2'
   },
]
const App = (props) => {


  return ( 
  <svg
    width={247}
    height={160}
    viewBox="0 0 247 160"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
    {...props}
  >
    <g id='el-1'>
      <rect width={57} height={62} />
      <foreignObject width={57} height={62}>
        <div className="item">
          <div className="category">{data[0].label}</div>
          <div className="label">{data[0].category}</div>
        </div>
      </foreignObject>
    </g>
    <g id='el-2'>
      <rect x={76} width={82} height={62} />
      <foreignObject x={76} width={82} height={62}>
        <div className="item">
          <div className="category">{data[1].label}</div>
          <div className="label">{data[1].category}</div>
        </div>
      </foreignObject>
    </g>
  </svg>
  )
}

ReactDOM.render(<App/>, document.getElementById("root"))
.item {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background:#D9D9D9
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

0 Answers
Related