K
K
Kote2020-09-28 22:24:10
React
Kote, 2020-09-28 22:24:10

How to correctly forward variables in a react component?

Sorry in advance, I'm new. At all.

Task:
to implement a convenient insertion of svg files into a web page, while forming a sprite. We insert the icon using use The

plugin is used https://github.com/JetBrains/svg-sprite-loader

I set it up and everything works like this:

import logo from "../images/svg/logo.svg";

 <svg>
    <use xlinkHref={`#${logo.id}`} />
  </svg>


The sprite is inserted, the id is set correctly, the svg is displayed perfectly. When assembling, logo.id is replaced with the actual symbol name from the sprite.

Problem:
I'd like to get a generic component where the title (the svg ID of the symbol to insert) can be set. as a variable. I try this and it doesn't work :

const Icon = ({symbolname}) => (
  <svg>
    <use xlinkHref={`#${`${symbolname}.id`}`}/>
  </svg>
);

<Icon symbolname="logo" />


It turns out that the variable from this component is accepted ok - after compiling I get the logo.id on the page, but I don’t understand how to force the second step to expand the real id.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nikolaev, 2020-09-29
@Heian

You don't have to do that. It is pointless. You import a whole file to get an ID from it, so that this ID can be passed to another component, so that it then receives the same file from the sprite by this ID, jizuz krist ... I'm not an expert, but the path looks spoiled by excessive zeal for over - engineering.
Instead, pass the ID as a string. You will make the sprite separately during assembly, and instead of the ID, you simply pass the name of the icon manually. This is actually no different from manually importing, but much simpler and more beautiful.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question