How can I customize the checked state of a checkbox when using svgr in React?

Viewed 28

I'm working on a React project and I'm using styled-component and typescript.

I'm customizing the checkbox like this:

Source

import React, { ReactElement } from 'react';
import styled from 'styled-components';
import IconChecked from '@assets/Icons/ico_checked.svg';

interface Props {
  id: string;
}

const StyledCheckBox = styled.input`
  box-sizing: border-box;
  width: 20px;
  height: 20px;
  background: #ffffff;
  border: 1px solid #d4dae4;
  border-radius: 4px;
  appearance: none;
  &:checked {
    background-image: url(${IconChecked});
    background-repeat: no-repeat;
    background-color: #ffffff;
    background-position: 50%;
  }
`;

const CheckBox = ({ id }: Props): ReactElement => (
  <StyledCheckBox type="checkbox" id={id} />
);

export default CheckBox;

Question

To use the svg icon without the <img> tag, I installed the svgr package and set it as an svg type loader through webpack. The problem is that svgr has the logic to convert svg to component, so I can't set the checked icon in the following way.

 &:checked {
    background-image: url(${IconChecked});
    ...
 }

As a result, the check icon(IconChecked) does not appear when I click the checkbox after using svgr. How can I solve this?

1 Answers

You can move your ico_checked.svg file to public folder and use the svg directly from the url like this:

 &:checked {
    background-image: url("/ico_checked.svg");
    ...
 }

You can take a look at this sandbox for a live working example of this approach.

Related