Skip to content
Advertisement

Dynamic styling of className not working in react

I am trying to code along to a tutorial video but the dynamic styling of className isn’t working. Though it seems to work on regular CSS, I’m using styled-components instead but I don’t get the same outcome. The end result is supposed to be a differently styled “type” according to its value. Please help

// import ContactContext from '../../context/contact/contactContext';

const ContactItemStyles = styled.div`
  .class-bg-light {
    color: grey;
  }
  .badge {
    font-size: 0.8rem;
    padding: 0.2rem 0.7rem;
    text-align: center;
    margin: 0.3rem;
    background: var(--green);
    color: #333;
    border-radius: 5px;
  }
  .badge-success {
    background: var(--green);
    color: #fff;
  }
  .badge-primary {
    background: red;
  }
`;
const ContactItem = ({ contact }) => {
  const { _id, name, email, phone, type } = contact;
  return (
    <ContactItemStyles>
      <div className='class-bg-light'>
        <h3 className='text-primary text left'>
          {name} {''} 
          <span
            className={
              'badge' +
              (type === 'professional' ? 'badge-success' : 'badge-primary')
            }
          >
            {type}
          </span>
        </h3>
      </div>
    </ContactItemStyles>
  );
};

ContactItem.propTypes = {
  contact: PropTypes.object.isRequired,
};

export default ContactItem;```

Advertisement

Answer

Almost there! Your mistake was concatenating the string values together inside className. Let’s say in your example that type is ‘professional’, what you would end up with looks like this:

className={'badge' + 'badge-success'} 
// This becomes 'badgebadge-success' 

You could add a space after your first class, or alternatively I would recommend using string interpolation via backticks: `

So your code should look like this:

className={`badge ${type === 'professional' ? 'badge-success' : 'badge-primary'}`}

Having the curly braces show where the strings are likely to end and start makes it clearer in case you missed any whitespace.

Keep up the learning and good luck!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement