Search code examples
cssreactjsstyled-components

Call function inside styled-components


I have a function that checks to see what the length of the passed in prop is and if the length is too long I want to adjust the font-size to be smaller. (I can't use a dynamic width because the component has a custom animation)

Current Code

const checkLength = () => {
  if (props.text.length > 7) {
    return "15px";
  } else {
    return "17px";
  }
};

const MyButton = styled.button`
  font-size: 17px;
`

I tried to write it like this but it doesn't read the function.

const MyButton = styled.button`
  font-size: checkLength();
`

Solution

  • Thanks for the code example. The checkLength function needs to be in a scope that is accessible from MyButton. In functions that you pass to the styled component template literals, you have access to all props that are passed to the component when rendered. I've expanded your code to include two usages of MyButton, take a look:

    const App = () => {
      return (
        <div>
          <MyButton text="hello">
            <span>hello</span>
          </MyButton>
          <MyButton text="yar">
            <span>yar</span>
          </MyButton>
        </div>
      )  
    }
      
    const checkLength = (props) => {
      if (props.text.length > 4) {
        return '20px';
      } else {
        return '24px';
      }
    }
    
    const MyButton = styled.button`
      font-size: ${checkLength};
    `
    
    ReactDOM.render(<App />, document.getElementById('app'));