Search code examples
reactjsstyled-components

Function to output styled-component


I have a stackblitz here

Its a super simple react app with a styled-component.

Is it possible to have a function to output the styled-component that I can pass in values like my attempt that is commented out.

I'd like to sue the Block styled-component but change the color each time

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import styled from 'styled-components'

export const Block = styled.div`
  width: 100px;
  height: 100px;
  background: red;
`

const createBlock = (col) => {
  return(
    Block = styled.div`
      width: 100px;
      height: 100px;
      background: col;
    `
  )
}

const App = () => {

  return (
    <div>
      <Block/>
      {createBlock(red)}
    </div>
  );
}

render(<App />, document.getElementById('root'));

Solution

  • I think you are looking for something like this:

    const createBlock = (col) => {
      return styled.div`
          width: 100px;
          height: 100px;
          background: ${col};
        `
    }
    
    const App = () => {
      const StyledBlock = createBlock('red');
    
      return (
        <StyledBlock>
          <p>Some content</p>
        </StyledBlock>
      );
    }