0

I have 2 repos:

  1. my main web app
  2. my shared component library, being imported as a node module through package.json

Both of them use React. In my main web app, I'm just importing the component files of my shared component library directly like so:

Switch.js (in my shared component library)

import React from 'react';
import { Switch } from 'antd';
import styled from 'styled-components';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';

const StyledSwitch = styled(Switch).attrs({
  checkedChildren: <CheckOutlined />,
  unCheckedChildren: <CloseOutlined />
})``;

export default StyledSwitch;

My main web app:

import Switch from 'my-shared-component-lib/components/Switch';

However, I'm getting this error:

../my-shared-component-lib/components/Switch.js
SyntaxError: /Users/edmundmai/Documents/src/my-shared-component-lib/components/Switch.js: Unexpected token (9:19)

   7 | 
   8 | const StyledSwitch = styled(Switch).attrs({
>  9 |   checkedChildren: <CheckOutlined />,
     |                    ^
  10 |   unCheckedChildren: <CloseOutlined />
  11 | })`
  12 |   &.ant-switch {

Is there something I have to install so that my imports will work?

1 Answer 1

1

I don't think you can use a React component as an object value in this manner:

{
  checkedChildren: <CheckOutlined />,
  unCheckedChildren: <CloseOutlined />
}

The < is not valid syntax for the start of an object value (hence the "Unexpected token" error).

What you may want to try instead is to use a Prop Factory offered by styled-components instead, e.g.:

const StyledSwitch = styled(props => <Switch
  checkedChildren={<CheckOutlined />}
  unCheckedChildren={<CloseOutlined />}
  {...props}
/>)``;

I haven't used the styled-components library, but I think it should work based on what I see in this code sandbox (which I derived from this official example from Ant Design's Switch documentation).

Here's a comment from the styled-components GitHub issues that might also be worth looking at.

Sign up to request clarification or add additional context in comments.

2 Comments

I just tried the syntax you suggested but it still didn't work. Same error. Thanks for the effort though
That's odd. There shouldn't be anything invalid about the syntax that would result in the same "Unexpected token" error if {<CheckOutlined />} and {<CloseOutlined />} are wrapped in curly braces on both sides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.