Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Necessary to `import React from 'react'` when using styled-components?

If I have a pure component that just takes some props and returns some jsx which is made up of components created 100% with styled-components, is it necessary to import React from 'react'?

I'm receiving an eslint error: react/react-in-jsx-scope because currently I'm not importing React from 'react', but my code still works just fine. This reason caused me to question whether or not I should be importing React here.

Here's a pretty basic example of what my pure component file looks like:

import styled from 'styled-components'

// pure function
const Block = props => {
  return (
    <BlockOuter>
      <BlockInner>{props.children}</BlockInner>
    </BlockOuter>
  )
}

// styled component
const BlockOuter = styled.div`
  display: flex;
  flex-direction: column;
  border: 1px solid #f2f2f2;
  height: ${props => props.height || 400}px;
  width: ${props => props.width}px;
`

// styled component
const BlockInner = styled.div`
  overflow: auto;
`
like image 326
jakewies Avatar asked Aug 10 '26 07:08

jakewies


1 Answers

Since React V16 you can return a string from your components.
So in some situations, a stateless component that returns a string will be just like any other component:

export const Hello = ({ name }) => `${name}`;

No need for react here.
Of course you will need react when you are using JSX.

Here is a small example to demonstrate it.
I'm not using a stack-snippet because it doesn't support files structure.

As for the eslint, i guess it's not up to date with the current version of react.

like image 150
Sagiv b.g Avatar answered Aug 12 '26 20:08

Sagiv b.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!