How to create custom attr name with styled component?

Viewed 43

Can u explain me how to use SC with custom attr name?

This code does not work and i dont understand why.

I expect to receive like this <div customAttrName="customAttrName"></div>

export const TagName = styled.div.attrs((props) => {
  console.log("props", props);
  return {
    type: "anyType",
    size: 25,
    customAttrName: "customAttrName"
  };
})`
  padding: 4px 7px 2px 10px;
  margin: 5px 6px 5px 0;
  border-radius: 5px;
  font-family: "MullerRegular", sans-serif;
`;

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <TagName>Start editing to see some magic happen!</TagName>
    </div>
  );
}
2 Answers

For customs data attributes you need to use the prefix data-*:

export const TagName = styled.div.attrs((props) => {
  console.log("props", props);
  return {
    type: "anyType",
    size: 25,
    data-customAttrName: "customAttrName"
  };
})`
  padding: 4px 7px 2px 10px;
  margin: 5px 6px 5px 0;
  border-radius: 5px;
  font-family: "MullerRegular", sans-serif;
`;

Using data attributes

I am not really sure what you are trying to achieve since you don't utilize the prop inside the styled-component styles, but usually I write something like this:

export const TagName = styled.div.attrs(() => ({
  customAttrName: 25,
}))<{ customAttrName: anyType }>`
  padding: 4px 7px 2px 10px;
  margin: 5px 6px 5px 0;
  border-radius: 5px;
  font-family: 'MullerRegular', sans-serif;
`
Related