This codemod is for fixing one of the deprecated features of styled-components in v4. Namely, number 7 mentioned here - https://www.styled-components.com/docs/faqs#what-do-i-need-to-do-to-migrate-to-v4.
Styled Components has deprecated the ability to pass in an object as an argument to the .attrs
function.
🚫
import styled from 'styled-components'
const Input = styled.input.attrs({
type: props => props.inputType,
})`
background: blue;
color: red;
`
✅
import styled from 'styled-components'
const Input = styled.input.attrs(props => ({
type: props.inputType,
}))`
background: blue;
color: red;
`
yarn global add jscodeshift
- Create a file in the root of your project (really whereever you would like) called
transforms/attrsObjectToFunction.js
and paste the codemod into the file. - run in the root of your project
jscodeshift -t transform/attrsObjectToFunction.js src
(or wherever your source is)
This codemod isn't 100% accurate. So watch out for the following:
This codemod does not verify that any call to a function called .attrs
is actually a Styled
object or call off of the Styled
object. So make sure to manually revert any .attrs
calls that may have been changed that are not a part of Styled
objects.
All this codemod does is it takes the first arg of each .attrs
call, checks to make sure it's an object, and then wraps that exact object in an arrow function with no parameters. A smarter codemod might check the object to see if there are any properties on that object that are functions to modify them as well, but this doesn't support that right now. See the example below for more information.
Example
In the example below the codemod would simply wrap that exact object in a parameterless arrow function which would still be invalid becasue the color
attr would need to be changed from a function to use props
passed into the new attrs function. You will need to manually catch all of the situations and fix them yourself.
export const MyStyledDiv = styled.div.attrs({
color: props => props.hasError ? 'red' : 'green'
})
Codemod Wrong Output
export const MyStyledDiv = styled.div.attrs(() => ({
color: props => props.hasError ? 'red' : 'green'
}))
Correct Output
export const MyStyledDiv = styled.div.attrs(props => ({
color: props.hasError ? 'red' : 'green'
}))
Please forgive me but I don't see any different between the wrong one and right one
vs
The only difference i'm seeing is you destructure the props on the correct one.