Change ToucheableOpacity color on click not working

46 Views Asked by At

Here is the code I am trying to change the color of the button being clicked. The plan is to have more buttons (one for each day of the week). On click - change the color of the button clicked and reset all other button colors to default. Right now I am hard-coding initialArr[0].color='red' but the plan is to put that in an if loop. When I click on the button, changeColorB2 is called but no change in color of the first button. TIA.

const initialArr = [
  {
    id: 1,
    color: "#e3e3e3",
    text: "Mon, 11",
  },
  {
    id: 2,
    color: "#e3e3e3",
    text: "Tue, 12",
  },
];

const changeColorB2 = (buttonInfo) => (e) => {
  console.log("Callllllleedddd ", buttonInfo);
  initialArr[0].color = "red";
};

const buttonsListArr = initialArr.map((buttonInfo) => (
  <TouchableOpacity
    style={{ backgroundColor: buttonInfo.color, flex: 1, padding: 15 }}
    onPress={changeColorB2(buttonInfo)}
    key={buttonInfo.id}
  >
    <Text>{buttonInfo.text}</Text>
  </TouchableOpacity>
));

<View style={{ flex: 1, marginRight: -1 }}>{buttonsListArr}</View>;
1

There are 1 best solutions below

3
DinhNguyen On BEST ANSWER

You should use useState to update color:

const initialArr = [
  {
    id: 1,
    color: "#e3e3e3",
    text: "Mon, 11",
  },
  {
    id: 2,
    color: "#e3e3e3",
    text: "Tue, 12",
  },
];
const [data, setData] = useState(initialArr)

const changeColorB2 = (buttonInfo, index) => {
  console.log("Callllllleedddd ", buttonInfo);
  let newArr = [...data];
  newArr[index].color = "red";
  setData(newArr);
};

const buttonsListArr = data.map((buttonInfo, index) => (
  <TouchableOpacity
    style={{ backgroundColor: buttonInfo.color, flex: 1, padding: 15 }}
    onPress={() => changeColorB2(buttonInfo, index)}
    key={buttonInfo.id}
  >
    <Text>{buttonInfo.text}</Text>
  </TouchableOpacity>
));

<View style={{ flex: 1, marginRight: -1 }}>{buttonsListArr}</View>;