Search code examples
reactjsstyled-components

when should I pass 'className' props to react component?


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)``;

Solution

  • 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.