1

I try to apply Styled Components to my React code with TypeScript.
Now my render() method generates multiple elements with loop, and each element's className is generated dynamically by another method.

render() {
    try {
      const {steps} = this.props;
      return (
        <div className="step-bar">
          {steps.map((s, i) => (
            <div key={i} className={this.getClassName(i)}>
              {s}
            </div>
          ))}
        </div>
      );
    } catch(e) {
      utils.sendErrorObject(e);
      return null;
    }
  };

Now I want to apply Styled Component to this code and handle multiple styles according to className, but I don't know how to specify the condition because className is dynamic in the code.
Anyone knows good idea?

lipsum
  • 919
  • 2
  • 13
  • 24

1 Answers1

0

Try this:

import styled from 'styled-components';

const MyStyledComponent = styled.div`
   background-color: ${props => ~props.className.indexOf('current') ? 'red' : 'blue'}
`

...

render() {
   return <MyStyledComponent className={this.getClassName(i)}>Text</MyStyledComponent>
}
NirG
  • 746
  • 5
  • 12
  • The result of getClassName is like “step” or “step__current” etc, and I want to change the background color when the className includes “current”. – lipsum Aug 04 '19 at 22:58
  • check this toggle solution, it worked for me - https://stackoverflow.com/a/196038/984471 – Manohar Reddy Poreddy Jun 09 '21 at 07:46