VihangaAW
VihangaAW

Reputation: 322

Check component 's style using a loop

I have created a collection of buttons using a loop. Background color of those buttons change one by one, one button at a time. Is there any way to get the key of the button which background color is black when the function is called.

export default class App extends Component<Props> {
  constructor(props) {
        super(props);
        this.state = {
            selectedControl: 0,
            controls: ["TITLE1", "TITLE2", "TITLE3"]
        };

    }

  componentDidMount() {
        this.timerHandle = setInterval(() => {
            this.setState(({selectedControl, controls}) =>
               ({selectedControl: (selectedControl + 1) % controls.length})
            );
        }, 1000);
    }

  render() {
    const {selectedControl, controls} = this.state;
    return (
      <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap',  justifyContent: 'space-evenly',
      alignItems: 'stretch' }}>
      {controls.map((control, index) => (
          <Button key={control}  title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
          ))}
    </View>
    );
  }
}

const styles = StyleSheet.create({
  buttonStyle: {
     height: '100%', 
  },
  highlighted: {
    height: '100%',
    backgroundColor: 'black', 
  }
});

Upvotes: 1

Views: 36

Answers (1)

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

The button keys are set to control. So, check for when the button is highlighted (i.e. index === selectedControl) in render and the button's key is control.

<View style={{
  flex: 1,
  flexDirection: 'row',
  flexWrap: 'wrap',
  justifyContent: 'space-evenly',
  alignItems: 'stretch'
}}>
  {controls.map((control, index) => {
    if (index === selectedControl) {
      console.log({"key": control}) /* <-- here */
    }
    return <Button key={control}  title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
  })}
</View>

Upvotes: 1

Related Questions