Search code examples
javascriptreactjsdynamicrenderstyled-components

Dynamically change styled component based on state AND index


So I have a list that was returned from an API request (not important) lets call it list = [1,2,3,4,5,6,7];

Now, inside render(), I have something like the following

render(){
  <Wrapper>
    {list.map((i) => {
      return (<Button id = {i} onClick = {this.customFunc.bind(this, i)} />)
    }
  </Wrapper>
}

Now, I have another list, lets call it list_check = [false...] (for all 7 elements listed above)

Assume that customFunc changes the respective button id in list_check from false to true.

e.g. if I clicked button 1 (id = 1) then list_check becomes [false, true, false...]

** Now my problem is: I have 2 styled components, Button and Button_Selected, how can i dynamically change between the 2 styled components so that if that unique button is clicked (change list_check[index] = true), the element becomes Button_Selected instead of Button (The entire list is initalized as Button since all elements are false)

Just to make it clear: Both arrays are located in this.state and by 2 styled components I mean there exists

const Button = styled.div`
  //styling here
`;

and

const Button_Selected = Button.extend`
 //Small styling change to differentiate between selected and not selected
`;

edit: all answers are great! too bad I can only select one :(


Solution

  • You could just save the component to another variable.

    this.state.list_check.map((item, i) => {
        const NecessaryButton = item ? SelectedButton : Button;
        return <NecessaryButton onClick={() => this.makeSelected(i)}>Normal Button</NecessaryButton>
    })
    

    You can see a live example here.