The goal I have is to click on the button and for the button to change color until I click it again. I had the code working with a single button but when I tried to make an array of buttons I ran into trouble, I feel like I misses something obvious but can't find it
//GRID.js
import React, { useState, useEffect } from "react";
import { Cell } from "./cell";
export const Grid = () => {
const ARRAYLENGTH = 3;
const [grid, setGrid] = useState(Array(ARRAYLENGTH).fill({ show: true }));
useEffect(() => {
console.log("updated");
}, [grid]);
const handlePress = (index) => {
let tempGrid = grid;
tempGrid[index].show = !tempGrid[index].show;
setGrid(tempGrid);
console.log(grid[index].show);
logGrid();
};
const logGrid = () => {
console.log(grid);
};
//Renders cell.js
return grid.map((item, index) => {
return (
<Cell
key={`${item} ${index}`}
show={grid[index].show}
index={index}
onClick={handlePress}
/>
);
});
};
//CELL.JS
import React, { useState, useEffect } from "react";
import styled from "styled-components/native";
import { View, Pressable } from "react-native";
import * as theme from "../../config/theme";
//Styles
const StyledCell = styled(Pressable)`
padding: 30px;
border-color: black;
border-width: 1px;
background-color: ${(props) => props.color};
`;
Here is the updated code for anyone who would like to see it
//grid.js
import React, { useState } from "react";
import { Cell } from "./cell";
export const Grid = () => {
const ARRAYLENGTH = 4;
const [grid, setGrid] = useState(
Array(ARRAYLENGTH)
.fill()
.map(() => ({ show: true }))
);
const handlePress = (index) => {
let tempGrid = [...grid];
tempGrid[index].show = !tempGrid[index].show;
setGrid(tempGrid);
};
return grid.map((item, index) => {
return (
<Cell
key={`${item} ${index}`}
show={item.show}
index={index}
onClick={handlePress}
/>
);
});
};
//cell.js
import React, { useState, useEffect } from "react";
import styled from "styled-components/native";
import { View, Pressable } from "react-native";
import * as theme from "../../config/theme";
const StyledCell = styled(Pressable)`
padding: 30px;
border-color: black;
border-width: 1px;
background-color: ${(props) => props.color};
`;
export const Cell = ({ show, onClick, index }) => {
const [color, setColor] = useState(theme.blue);
useEffect(() => {
if (show === true) {
setColor(theme.blue);
} else {
setColor(theme.white);
}
}, [show]);
return (
<View>
<StyledCell
color={color}
onPress={() => {
onClick(index);
}}
/>
</View>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.