Reputation: 1121
Some react components pass the className props to the child component.
I haven't seen any need for passing className
as a prop in my projects.
why this className
props is been used ? and when should i adopt this approach?
import styled from 'styled-components'
const ReactComponent = ({ className }) => {
return <div className={className}/>
}
const StyledComponent = styled(ReactComponent)``;
Upvotes: 4
Views: 8111
Reputation: 162
You generally add classes to create a style or JavaScript code snippet that effects more than one element. Here is an explanation of how to use classes.
This particular component uses StyledComponent, but it's possible that the user wanted to add a class to add extra styles on top of those for the default in specific cases.
It's also possible that the classes are used to toggle some effect in JS. I've linked examples of each case.
Without more code it's hard to say why this particular user passed down a className, but there are certainly cases where you could want to, or when you could do without passing down a className. If your code doesn't seem to require it, there's definitely no reason to add it in.
Upvotes: 0
Reputation: 42536
It really depends on the context, but generally, the className
prop is passed down from parent to child to either overwrite, or append the existing className
on the child component.
This is particularly useful in the scenario when you are building reusable base components which needed to be easily extended and customised.
Given your example,
const ReactComponent = ({ className }) => {
return <div className={className}/>
}
Let's say we have a parent component which renders the child ReactComponent
, and we need to customise the stylings for this instance:
return (
<div className='container'>
<ReactComponent className='is-red' />
<ReactComponent className='is-blue'/>
</div>
)
This will allow the parent to render both components, with different styles, and without the need to repeat the same code.
Upvotes: 5