D
D
danil_linkins2018-05-08 13:53:20
css
danil_linkins, 2018-05-08 13:53:20

How to organize state transfer from react to svg?

Let's say we have one svg file. I inject a file into a component through a plugin and get the output ..., which I can control.
The bottom line is that the icon has 4 possible states, with animation between transitions to these states.
What is the best way to organize this management?
If I can still write animation directly in svg, then with the state everything is more difficult.
Are there any already proven methods and methods?
Since it's not practical to use css for several files appearing and disappearing, as I think. Even for reuse there will be difficulties.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-05-08
@danil_linkins

It is better to create a sprite and add it to the document, and pick up icons by id.
Component using Styled Components as an example :

import React from 'react';
import styled from 'styled-components';

const SVG = styled.svg`
  display: inline-block;
  vertical-align: middle;
`;

const Icon = ({ name, ...props }) {
  if (!name) {
    throw new Error('Unknown icon name!');
  }
  return (
    <SVG {...props}>
      <use xlinkHref={`#icon-${name}`} />
    </SVG>
  );
}

export default Icon;

Stylized icon with different states:
import React from 'react';
import styled from 'styled-components';
import { Icon } from './components';

const StyledIcon = styled(Icon)`
  fill: ${props => props.state.fill};
`;

const Example = ({ iconState }) => <StyledSVG name="profile" state={iconState} />;

export default Example;

Styled Components , this is just an example. Such components are easily implemented without using this library.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question