javascriptreactjsstyled-componentsmodularity

Structuring and reusing React Styled-components and native components


I’m a backend engineer who is learning frontend – very much a noob at this point. I’m currently learning React and came across styled-components¬, which seems like a great way of handling styling whilst using components. I’m currently having issues using styled-components with native [React] components and changing them in a modular fashion. I can’t think of a viable option of doing what I want to do, or more likely, I’m doing it wrong. Use case: Here my folder setup:

enter image description here

I’ve decided to include two files for each component:

Here the styles.js:

const StyledDeleteButton = styled.button`
    width: auto;
    height: 30px;

    font-size: 20px;
    text-align: center;
    color: green;

    border: none;
    border-radius: 5px;

    &:hover {
        color: red;
    }
`;

Here the components.js:

const DeleteButton = () => <StyledDeleteButton>Delete</StyledDeleteButton>;

What I want to achieve: In my styles, I don’t want to apply any positioning now - but can later via props of course. But I want to use the native component which has the Delete text. So, my question is, how can I apply addition styling on the component?

Inheriting the native component, but doesn't seem possible. I can apply what I want via CSS but want to be consistent as I can.


Solution

  • If you don't want to apply any styles for now and do it later, you can pass className as a prop like this, and just use the native <button /> element

    const DeleteButton = ({className}) => <button className={className}>Delete</button>;
    

    Then later for adding styles, you have to use the styled function on the DeleteButton component

    const StyledDeleteButton = styled(DeleteButton)`
        width: auto;
        height: 30px;
    
        font-size: 20px;
        text-align: center;
        color: green;
    
        border: none;
        border-radius: 5px;
    
        &:hover {
            color: red;
        }
    `;
    

    Styling any component from the doc