Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  83] [ 2]  / answers: 1 / hits: 28932  / 5 Years ago, thu, may 30, 2019, 12:00:00

I came across the .attrs() function in styled components, but I do not understand what it does, or what it does differently?


I tried to understand the example in their docs, but as far as I am concerned, I can do the exact same thing without the attrs() function.


Could somebody please explain this to me or give a simple example?


More From » html

 Answers
21

Focus on naming is very important.


Styled components as the name suggests are for styling the native DOM elements or custom components.


attrs is for mentioning the attributes of that very same DOM element in the attrs constructor without the need to even mention it in actual component call.


What above line means is you can do


 <Input placeholder="A small text input" />

with


const Input = styled.input.attrs(({ type }) => ({
type: type || "password"
}))`
align-items: center;
display: flex;
margin: 1.5vh 0;
`

See that component usage <Input .../> doesn't have type prop anywhere. It came from your attribute constructor function(static)


You couldn't have done this otherwise in your style rules because these are just the string literal of your CSS properties.


It saved you from writing type='password' in every usage of


<Input type='password' ... />


Bonus:


Now, that's a specific input component with type attribute of password. What if you wish to have a general input (styled component) with any value of type attribute?


Tada!



const Input = styled.input.attrs(({ type }) => ({

type: type || "password",
...


Your type is now dynamic i.e. it will take whatever input type prop you specify from your usage of component and render the input as that type (text, password, file etc. ) or if you skip the type prop it will pick up default of password. You can use as much conditional logic as you want up there.


Example:


<Input .../> // renders type="password"
<Input type="text" .../>
<Input type="email" .../>

Hope that answers your question.


[#52061] Wednesday, May 22, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anayaashleyh

Total Points: 597
Total Questions: 96
Total Answers: 86

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
anayaashleyh questions
;