Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does the '$' do in React component props?

I am studying styled-component, and I faced some problems in ‘adapting based on props’ part.

import './App.css';
import styled from 'styled-components'

const PrimaryButton = styled.button`
  color: ${props=>props.primary?"white":"black"};
  background-color: ${props=>props.primary?"blue":"gray"};
`;

function App() {
  return (
    <div>
      <PrimaryButton>Normal</PrimaryButton>
      <PrimaryButton primary>Primary</PrimaryButton>
    </div>
  );
}

export default App;

At first, I tried with this code, and the console told me to use primary=true, so I did.

But there was a following error in the console which says ‘it looks like an unknown prop "primary" is being sent through to the DOM’. To solve this problem, I briefly scanned the styled-components document. I found out that they use $primary instead of primary. So the final code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import './App.css';
import styled from 'styled-components'

const PrimaryButton = styled.button`
  color: ${props=>props.$primary?"white":"black"};
  background-color: ${props=>props.$primary?"blue":"gray"};
`;

function App() {
  return (
    <div>
      <PrimaryButton>Normal</PrimaryButton>
      <PrimaryButton $primary>Primary</PrimaryButton>
    </div>
  );
}

export default App;

I could no longer see the errors, but still I don’t know the reason it happened and is solved.

What does $ mean?

>Solution :

These are used by styled-components and they have nothing to do with React.

If you want to prevent props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.

you can learn more here you can find an example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading