Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass custom attribute to a styled component in a functional component?

I'm trying to understand how this thing works, but all examples that I found was written in a class fashion.

   import React from 'react'
   import styled from 'styled-components/native'

   const MyTag = styled.Button.attrs({
     title: myThisThingValue
   })`
     // some style
     background: thisIsAlsoMyThingValue
   \` 

   export default function MyComponent({ props }) {
     return(
       <MyTag myThisThing="My value" thisIsAlsoMyThing="Other Value" />
         )
   }

I'm just want access to my custom attributes in the MyTag styled. I used a (props) => {title: props.MyThing } in .attrs() but didn't work.

like image 726
Cristiano Avatar asked May 22 '19 13:05

Cristiano


2 Answers

that should work:

JavaScript Version:

export const MyTag = styled.button.attrs(props => ({
  title: props.myThisThingValue,
}))`
  background: ${props => props.thisIsAlsoMyThing};
`;

TypeScript Version:

interface MyTagProps {
  myThisThingValue: string;
  thisIsAlsoMyThing: string;
}

export const MyTag = styled.button.attrs((props: MyTagProps) => ({
  title: props.myThisThingValue,
}))<MyTagProps>`
  background: ${props => props.thisIsAlsoMyThing};
`;

Use it:

<MyTag myThisThingValue="My value" thisIsAlsoMyThing="red" />
like image 99
Bianca Avatar answered Nov 17 '22 01:11

Bianca


In this case title is a defined attribute, but if you need a data attribute like indexNumber (not defined attribute) you will need to use the prefix data-*:

export const TagName = styled.button.attrs((props) => {
  return {
    data-indexNumber: "indexNumber value"
  };
})``;

Using data attributes

like image 4
lissettdm Avatar answered Nov 17 '22 01:11

lissettdm