Component not displaying updated data when field is updated? - javascript

I have a table that is populated with data from an array of objects.
This data is collected via websockets. The socket listens to 3 different events, and does one of the following to the array based on the event:
User can add an entry - ✅ works fully
User can modify an entry - issue
User can delete an entry - ✅ works fully
Here is the code:
interface TableEntry {
address: string;
amount: string;
children?: React.ReactNode;
}
export const TableComponent: FC = () => {
const socket = useContext(SocketContext);
const [entriesArray, setEntriesArray] = useState<TableEntry[]>([]);
const { globalAddress } =
useContext(UserDetailsContext);
useEffect(() => {
socket.on("end", (data) => {
setEntriesArray([]);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
var tempEntries = entriesArray;
socket.on("entry", (data) => {
tempEntries.push({ address: data[0], amount: data[1] });
setEntriesArray(tempEntries);
tempEntries = [];
});
return function () {
socket.off("entry");
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
//Update an entry on request from a user
useEffect(() => {
var tempEntries = entriesArray;
socket.on("updateEntry", (data) => {
const findFunc = (element: TableEntry) => element.address == data[0];
const index = tempEntries.findIndex(findFunc);
tempEntries[index].address = "updated address";
setEntriesArray(tempEntries);
tempEntries = [];
});
return function () {
socket.off("updateEntry");
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<Box>
<Box
w="427px"
h="450px"
top={"72px"}
right={"60px"}
bg={"rgba(255, 255, 255, 0.08)"}
position={"absolute"}
borderRadius="21"
overflow="hidden"
>
<TableContainer>
<Table variant="simple">
<Thead>
<Tr>
<Th fontFamily={"Orbitron"}>Address</Th>
<Th fontFamily={"Orbitron"}>Amount</Th>
</Tr>
</Thead>
<Tbody>
{entriesArray?.map((entry) => {
return entry.address == globalAddress ? (
<Tr key={entry.address} bg={"rgba(255, 255, 255, 0.05)"}>
<Td fontFamily={"Orbitron"}>{shorten(entry.address)}</Td>
<Td fontFamily={"Orbitron"}>{entry.amount}</Td>
</Tr>
) : (
<Tr key={entry.address}>
<Td fontFamily={"Orbitron"}>{shorten(entry.address)}</Td>
<Td fontFamily={"Orbitron"}>{entry.amount}</Td>
</Tr>
);
})}
</Tbody>
</Table>
</TableContainer>
</Box>
</Box>
</>
);
};
The data updates, but it is not being displayed in the table - how can I make sure the data in the table reflects the update?
I assumed since I am changing the state of entriesArray that forced a rerender - but that doesn't seem to be the case?

React's state is immutable, so you cannot update an array item directly. You need to use map with {...element} for cloning and updating that array item at the same time.
useEffect(() => {
socket.on("updateEntry", (data) => {
const tempEntries = entriesArray.map((element: TableEntry) =>
element.address == data[0]
? { ...element, address: "updated address" } //update the found element
: element //keep the original element
);
setEntriesArray(tempEntries);
tempEntries = [];
});
return function () {
socket.off("updateEntry");
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Note that, you also can clone the entire array with a spread operator like [...entriesArray] or cloneDeep before updating any element, but it's not preferable because it means you want to render the entire array (even though you want to render the updated element only) which hits performance if you have a huge array.

Related

Array with inputs in React

Im trying to create a table with an array of products, the problem I have is that the inputs take the value of any input with the same "name". Also, when I try to remove any of the products, it always removes the last one.
https://stackblitz.com/edit/react-gto9bw?file=src/App.js
const [producto, setProducto] = useState({
codigo: '',
nombre: '',
descripcion: '',
precio: '',
cantidad: '',
estado: '',
});
const [productos, setProductos] = useState([]);
const addProducto = () => {
setProductos([...productos, producto]);
};
const removeProducto = (e, index) => {
e.preventDefault();
const list = [...productos];
list.splice(index, 1);
setProductos(list);
};
const handleInputChangeProducto = (e, index) => {
e.preventDefault();
const { name, value } = e.target;
const list = [...productos];
list[index][name] = value;
setProductos(list);
};
The return its a table that has a button to add the product
return (
<div>
<table className="table-size" style={{ border: '1px solid black' }}>
<thead>
<tr>
<th scope="col">Nombre</th>
<th scope="col">Descripcion</th>
</tr>
{productos.map((producto, index) => (
<tr key={index}>
<td>
<input
name="nombre"
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
<td>
<input
name="descripcion"
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
<td onClick={(e) => removeProducto(e, index)}>
<Button>Borrar Producto {index}</Button>
</td>
</tr>
))}
</thead>
</table>
<br />
<button onClick={addProducto}>Crear Producto</button>
</div>
I've tried separating the "tr" into a separate component but that doesn't work either.
This is a common issue when using map with index instead of unique key.
So you can try like this:
Please add a global variable key in your case.
let key = 0;
Then set this key in your producto and increase it.
(In my full code, I used codigo as a key field.)
It should always be increased.
On backend API, you should get unique key as well.
Here is a full code.
import React, { useState } from 'react';
import { Button } from 'react-bootstrap';
import './style.css';
let key = 0;
export default function App() {
const [producto, setProducto] = useState({
codigo: '',
nombre: '',
descripcion: '',
precio: '',
cantidad: '',
estado: '',
});
const [productos, setProductos] = useState([]);
const addProducto = () => {
setProductos([...productos, { ...producto, codigo: ++key }]);
};
const removeProducto = (e, index) => {
e.preventDefault();
const list = [...productos];
list.splice(index, 1);
setProductos(list);
};
const handleInputChangeProducto = (e, index) => {
e.preventDefault();
const { name, value } = e.target;
const list = [...productos];
list[index][name] = value;
setProductos(list);
};
console.log({ productos });
return (
<div>
<table className="table-size" style={{ border: '1px solid black' }}>
<thead>
<tr>
<th scope="col">Nombre</th>
<th scope="col">Descripcion</th>
</tr>
{productos.map((producto, index) => (
<tr key={producto.codigo}>
<td>
<input
name="nombre"
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
<td>
<input
name="descripcion"
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
<td onClick={(e) => removeProducto(e, index)}>
<Button>Borrar Producto {index}</Button>
</td>
</tr>
))}
</thead>
</table>
<br />
<button onClick={addProducto}>Crear Producto</button>
</div>
);
}
Although the other answers are not wrong - and they all (implicitly) fixed the issues below, I wanted to call out the root cause of the problem you were seeing. It's not the use of indexes as keys (although having unique keys is a good idea for performance reasons).
When you created a new producto (at least in your original code sample), you were doing this:
const addProducto = () => {
setProductos([...productos, producto]);
};
Note the new producto being added to the array is always the same object. That means that your array contains a list of pointers that are all pointing to the same object. Modifying one will modify all of them. That's probably not what you want. Instead, do this:
const addProducto = () => {
setProductos([...productos, {...producto} ]);
};
That spreads the properties of your blank producto object onto a new object and ensures that each object in the array is really a separate thing.
The form's values were not actually controlled by the state. Going from your original code sample, make these changes:
{productos.map((producto, index) => (
<tr key={index}>
<td>
<input
name="nombre"
value={producto.nombre} // <-- this was missing. without it there is no relation between what the user is seeing in the input and what value is stored in the productos array.
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
<td>
<input
name="descripcion"
value={producto.descripcion} // <-- Same thing here
onChange={(e) => handleInputChangeProducto(e, index)}
/>
</td>
You need an unique key. Try to generate this unique key on your addProducto:
const addProducto = () => {
setProductos([...productos, { ...producto, id: Date.now() }]);
};
And then on your productos.map pass this generated id in your <tr key={producto.id}>.
Its recommended you have "static" indexes as key, React will understand better how manipulate your list and if occurs any modifications in this list, he will not recalculate everything.
Another point, if you need to manipulate something that depends of your previous state, like these add or remove operations, try to use functions for updates, like:
const addProducto = () => {
setProductos(prevProductos => [...prevProductos, { ...producto, id: Date.now() }]);
};
const removeProducto = (e, index) => {
e.preventDefault();
setProductos(prevProductos => [...prevProductos.slice(0, index), ...prevProductos.slice(index + 1)]);
};
Add an id field to your product JSON.
const [producto, setProducto] = useState({
id: '',
codigo: '',
nombre: '',
descripcion: '',
precio: '',
cantidad: '',
estado: '',
});
Update the ID for every product addition,
const addProducto = () => {
setProductos([...productos, {id: (prodcutos.length + 1), ...producto}]);
};
Replace your current key from index to producto.id,
{productos.map((producto, index) => (
<tr key={producto.id}>
Pass this id as param for you handleInputChangeProducto function,
<td>
<input
name="nombre"
onChange={(e) => handleInputChangeProducto(e, producto.id)}
/>
</td>
<td>
<input
name="descripcion"
onChange={(e) => handleInputChangeProducto(e, producto.id)}
/>
</td>
<td onClick={(e) => removeProducto(e, producto.id)}>
<Button>Borrar Producto {index}</Button>
</td>
const addProducto = () => {
setProductos((list) => [
...list,
{
id: list.length, //this should be unique anyway
codigo: '',
nombre: '',
descripcion: '',
precio: '',
cantidad: '',
estado: '',
},
]);
};
const removeProducto = (e, id) => {
setProductos((list) => {
list.splice(id, 1);
return [...list]
});
};
you should change your list in callback manner as shown.

React - How can I parse large JSON objects for graphing. Struggling to do so with State

I'm having trouble parsing large JSON objects from my Axios calls and setting them as a state to then be passed as X and Y axis data for graphing in react-chartist. For my case, I'm charting stock market data.
I have been trying to parse the data using state hooks, chartData, but can't get it working, like so response.data.symbol, response.data.adj_close, and response.data.date
I also tried creating three different states, for X, Y, and symbol data taken directly from the axios call, but wasn't able to accomplish so.
Here is the code I'm using:
export default function Graph() {
const [chartData, setChartData] = useState([])
const getData = () => {
axiosInstance
.get('price/' + slug)
.then(result => setChartData(result.data))
}
useEffect(() => {
getData()
}, [])
const graphChart = () =>
{
var data = {
labels: //date values from JSON object
series: //adj_close values from JSON object
};
var options = {
width: 500,
height: 400
};
return (
<ChartistGraph data={data} options={options} type="Line" />
);
};
return (
<Container>
<Grid>
{graphChart()}
</Grid>
</Container>
);
};
Am I approaching this wrong? Is there a simpler way to do so?
I've added the data to replicate the problem, which basically is, how can I parse large objects like this? Keeping in mind that each row needs to be grouped by it's respective symbol for graphing. In the data below, there are 8 companies worth of data. Putting all of this data on a graph would be bad, but if I knew how to parse specific symbols, then I will be able to accomplish graphing on my own.
[{"symbol":"PG","date":"2020-12-04","adj_close":137.47},
{"symbol":"HSY","date":"2020-12-04","adj_close":150.87},
{"symbol":"CLX","date":"2020-12-04","adj_close":199.98},
{"symbol":"COST","date":"2020-12-04","adj_close":373.43},
{"symbol":"MDLZ","date":"2020-12-04","adj_close":59.03},
{"symbol":"K","date":"2020-12-04","adj_close":62.37},
{"symbol":"KHC","date":"2020-12-04","adj_close":34.12},
{"symbol":"PEP","date":"2020-12-04","adj_close":145.85},
{"symbol":"PG","date":"2020-12-07","adj_close":137.68},
{"symbol":"HSY","date":"2020-12-07","adj_close":149.72},
{"symbol":"CLX","date":"2020-12-07","adj_close":200.61},
{"symbol":"COST","date":"2020-12-07","adj_close":373.33},
{"symbol":"MDLZ","date":"2020-12-07","adj_close":58.41},
{"symbol":"K","date":"2020-12-07","adj_close":61.95},
{"symbol":"KHC","date":"2020-12-07","adj_close":33.6},
{"symbol":"PEP","date":"2020-12-07","adj_close":145.37},
{"symbol":"PG","date":"2020-12-08","adj_close":138.05},
{"symbol":"HSY","date":"2020-12-08","adj_close":150.63},
{"symbol":"CLX","date":"2020-12-08","adj_close":202.88},
{"symbol":"COST","date":"2020-12-08","adj_close":377.6},
{"symbol":"MDLZ","date":"2020-12-08","adj_close":58.29},
{"symbol":"K","date":"2020-12-08","adj_close":62.55},
{"symbol":"KHC","date":"2020-12-08","adj_close":34.34},
{"symbol":"PEP","date":"2020-12-08","adj_close":145.52},
{"symbol":"PG","date":"2020-12-09","adj_close":136.41},
{"symbol":"HSY","date":"2020-12-09","adj_close":152.14},
{"symbol":"CLX","date":"2020-12-09","adj_close":200.51},
{"symbol":"COST","date":"2020-12-09","adj_close":374.29},
{"symbol":"MDLZ","date":"2020-12-09","adj_close":57.72},
{"symbol":"K","date":"2020-12-09","adj_close":62},
{"symbol":"KHC","date":"2020-12-09","adj_close":34.22},
{"symbol":"PEP","date":"2020-12-09","adj_close":145.69},
{"symbol":"PG","date":"2020-12-10","adj_close":135.51},
{"symbol":"HSY","date":"2020-12-10","adj_close":149.7},
{"symbol":"CLX","date":"2020-12-10","adj_close":200.6},
{"symbol":"COST","date":"2020-12-10","adj_close":372.79},
{"symbol":"MDLZ","date":"2020-12-10","adj_close":57.18},
{"symbol":"K","date":"2020-12-10","adj_close":61.98},
{"symbol":"KHC","date":"2020-12-10","adj_close":34.1},
{"symbol":"PEP","date":"2020-12-10","adj_close":144.67},
{"symbol":"PG","date":"2020-12-11","adj_close":136.51},
{"symbol":"HSY","date":"2020-12-11","adj_close":149.11},
{"symbol":"CLX","date":"2020-12-11","adj_close":201.73},
{"symbol":"COST","date":"2020-12-11","adj_close":375.1},
{"symbol":"MDLZ","date":"2020-12-11","adj_close":57.4},
{"symbol":"K","date":"2020-12-11","adj_close":62.11},
{"symbol":"KHC","date":"2020-12-11","adj_close":34.07},
{"symbol":"PEP","date":"2020-12-11","adj_close":144.97},
{"symbol":"PG","date":"2020-12-14","adj_close":135.85},
{"symbol":"HSY","date":"2020-12-14","adj_close":149.14},
{"symbol":"CLX","date":"2020-12-14","adj_close":202.38},
{"symbol":"COST","date":"2020-12-14","adj_close":374.38},
{"symbol":"MDLZ","date":"2020-12-14","adj_close":57.29},
{"symbol":"K","date":"2020-12-14","adj_close":61.92},
{"symbol":"KHC","date":"2020-12-14","adj_close":34.42},
{"symbol":"PEP","date":"2020-12-14","adj_close":144.23},
{"symbol":"PG","date":"2020-12-15","adj_close":136.65},
{"symbol":"HSY","date":"2020-12-15","adj_close":150.23},
{"symbol":"CLX","date":"2020-12-15","adj_close":203.04},
{"symbol":"COST","date":"2020-12-15","adj_close":371.88},
{"symbol":"MDLZ","date":"2020-12-15","adj_close":57.45},
{"symbol":"K","date":"2020-12-15","adj_close":61.24},
{"symbol":"KHC","date":"2020-12-15","adj_close":34.33},
{"symbol":"PEP","date":"2020-12-15","adj_close":144.77},
{"symbol":"PG","date":"2020-12-16","adj_close":137.27},
{"symbol":"HSY","date":"2020-12-16","adj_close":150.28},
{"symbol":"CLX","date":"2020-12-16","adj_close":203.44},
{"symbol":"COST","date":"2020-12-16","adj_close":369.44},
{"symbol":"MDLZ","date":"2020-12-16","adj_close":57.2},
{"symbol":"K","date":"2020-12-16","adj_close":61.5},
{"symbol":"KHC","date":"2020-12-16","adj_close":34.43},
{"symbol":"PEP","date":"2020-12-16","adj_close":144.89},
{"symbol":"PG","date":"2020-12-17","adj_close":138.25},
{"symbol":"HSY","date":"2020-12-17","adj_close":151.61},
{"symbol":"CLX","date":"2020-12-17","adj_close":202.34},
{"symbol":"COST","date":"2020-12-17","adj_close":370.29},
{"symbol":"MDLZ","date":"2020-12-17","adj_close":57.93},
{"symbol":"K","date":"2020-12-17","adj_close":62.48},
{"symbol":"KHC","date":"2020-12-17","adj_close":34.62},
{"symbol":"PEP","date":"2020-12-17","adj_close":145.71},
{"symbol":"PG","date":"2020-12-18","adj_close":139.04},
{"symbol":"HSY","date":"2020-12-18","adj_close":150.88},
{"symbol":"CLX","date":"2020-12-18","adj_close":203.17},
{"symbol":"COST","date":"2020-12-18","adj_close":367},
{"symbol":"MDLZ","date":"2020-12-18","adj_close":58.32},
{"symbol":"K","date":"2020-12-18","adj_close":62.08},
{"symbol":"KHC","date":"2020-12-18","adj_close":34.77},
{"symbol":"PEP","date":"2020-12-18","adj_close":146.93},
{"symbol":"PG","date":"2020-12-21","adj_close":137.52},
{"symbol":"HSY","date":"2020-12-21","adj_close":149.66},
{"symbol":"CLX","date":"2020-12-21","adj_close":202.45},
{"symbol":"COST","date":"2020-12-21","adj_close":364.97},
{"symbol":"MDLZ","date":"2020-12-21","adj_close":57.68},
{"symbol":"K","date":"2020-12-21","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-21","adj_close":34.57},
{"symbol":"PEP","date":"2020-12-21","adj_close":145.4},
{"symbol":"PG","date":"2020-12-22","adj_close":136.55},
{"symbol":"HSY","date":"2020-12-22","adj_close":148.62},
{"symbol":"CLX","date":"2020-12-22","adj_close":201.39},
{"symbol":"COST","date":"2020-12-22","adj_close":362.03},
{"symbol":"MDLZ","date":"2020-12-22","adj_close":57.16},
{"symbol":"K","date":"2020-12-22","adj_close":61.19},
{"symbol":"KHC","date":"2020-12-22","adj_close":34.39},
{"symbol":"PEP","date":"2020-12-22","adj_close":144.02},
{"symbol":"PG","date":"2020-12-23","adj_close":136.34},
{"symbol":"HSY","date":"2020-12-23","adj_close":149.45},
{"symbol":"CLX","date":"2020-12-23","adj_close":202.33},
{"symbol":"COST","date":"2020-12-23","adj_close":361.89},
{"symbol":"MDLZ","date":"2020-12-23","adj_close":57.35},
{"symbol":"K","date":"2020-12-23","adj_close":61.61},
{"symbol":"KHC","date":"2020-12-23","adj_close":34.8},
{"symbol":"PEP","date":"2020-12-23","adj_close":144.41},
{"symbol":"PG","date":"2020-12-24","adj_close":137.72},
{"symbol":"HSY","date":"2020-12-24","adj_close":149.95},
{"symbol":"CLX","date":"2020-12-24","adj_close":203.8},
{"symbol":"COST","date":"2020-12-24","adj_close":364.58},
{"symbol":"MDLZ","date":"2020-12-24","adj_close":57.85},
{"symbol":"K","date":"2020-12-24","adj_close":61.78},
{"symbol":"KHC","date":"2020-12-24","adj_close":34.98},
{"symbol":"PEP","date":"2020-12-24","adj_close":145.06},
{"symbol":"PG","date":"2020-12-28","adj_close":138.68},
{"symbol":"HSY","date":"2020-12-28","adj_close":151.8},
{"symbol":"CLX","date":"2020-12-28","adj_close":202.25},
{"symbol":"COST","date":"2020-12-28","adj_close":371.06},
{"symbol":"MDLZ","date":"2020-12-28","adj_close":58.27},
{"symbol":"K","date":"2020-12-28","adj_close":62.34},
{"symbol":"KHC","date":"2020-12-28","adj_close":35.21},
{"symbol":"PEP","date":"2020-12-28","adj_close":146.91},
{"symbol":"PG","date":"2020-12-29","adj_close":138.42},
{"symbol":"HSY","date":"2020-12-29","adj_close":151.44},
{"symbol":"CLX","date":"2020-12-29","adj_close":201.76},
{"symbol":"COST","date":"2020-12-29","adj_close":372.72},
{"symbol":"MDLZ","date":"2020-12-29","adj_close":58.45},
{"symbol":"K","date":"2020-12-29","adj_close":62.29},
{"symbol":"KHC","date":"2020-12-29","adj_close":34.9},
{"symbol":"PEP","date":"2020-12-29","adj_close":147.42},
{"symbol":"PG","date":"2020-12-30","adj_close":137.77},
{"symbol":"HSY","date":"2020-12-30","adj_close":150.53},
{"symbol":"CLX","date":"2020-12-30","adj_close":201.04},
{"symbol":"COST","date":"2020-12-30","adj_close":374.45},
{"symbol":"MDLZ","date":"2020-12-30","adj_close":58},
{"symbol":"K","date":"2020-12-30","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-30","adj_close":34.67},
{"symbol":"PEP","date":"2020-12-30","adj_close":147.31},
{"symbol":"PG","date":"2020-12-31","adj_close":139.14},
{"symbol":"HSY","date":"2020-12-31","adj_close":152.33},
{"symbol":"CLX","date":"2020-12-31","adj_close":201.92},
{"symbol":"COST","date":"2020-12-31","adj_close":376.78},
{"symbol":"MDLZ","date":"2020-12-31","adj_close":58.47},
{"symbol":"K","date":"2020-12-31","adj_close":62.23},
{"symbol":"KHC","date":"2020-12-31","adj_close":34.66},
{"symbol":"PEP","date":"2020-12-31","adj_close":148.3},
{"symbol":"PG","date":"2021-01-04","adj_close":137.82},
{"symbol":"HSY","date":"2021-01-04","adj_close":150.9},
{"symbol":"CLX","date":"2021-01-04","adj_close":200.44},
{"symbol":"COST","date":"2021-01-04","adj_close":380.15},
{"symbol":"MDLZ","date":"2021-01-04","adj_close":57.92},
{"symbol":"K","date":"2021-01-04","adj_close":61.45},
{"symbol":"KHC","date":"2021-01-04","adj_close":34.23},
{"symbol":"PEP","date":"2021-01-04","adj_close":144.27},
{"symbol":"PG","date":"2021-01-05","adj_close":138.7},
{"symbol":"HSY","date":"2021-01-05","adj_close":150.73},
{"symbol":"CLX","date":"2021-01-05","adj_close":200.01},
{"symbol":"COST","date":"2021-01-05","adj_close":375.74},
{"symbol":"MDLZ","date":"2021-01-05","adj_close":57.98},
{"symbol":"K","date":"2021-01-05","adj_close":61.8},
{"symbol":"KHC","date":"2021-01-05","adj_close":33.57},
{"symbol":"PEP","date":"2021-01-05","adj_close":144.7},
{"symbol":"PG","date":"2021-01-06","adj_close":140.16},
{"symbol":"HSY","date":"2021-01-06","adj_close":151.26},
{"symbol":"CLX","date":"2021-01-06","adj_close":197.41},
{"symbol":"COST","date":"2021-01-06","adj_close":370.02},
{"symbol":"MDLZ","date":"2021-01-06","adj_close":57.87},
{"symbol":"K","date":"2021-01-06","adj_close":61.32},
{"symbol":"KHC","date":"2021-01-06","adj_close":33.94},
{"symbol":"PEP","date":"2021-01-06","adj_close":142.93},
{"symbol":"PG","date":"2021-01-07","adj_close":138.85},
{"symbol":"HSY","date":"2021-01-07","adj_close":151.17},
{"symbol":"CLX","date":"2021-01-07","adj_close":196.43},
{"symbol":"COST","date":"2021-01-07","adj_close":367.92},
{"symbol":"MDLZ","date":"2021-01-07","adj_close":57.76},
{"symbol":"K","date":"2021-01-07","adj_close":60.89},
{"symbol":"KHC","date":"2021-01-07","adj_close":33.695},
{"symbol":"PEP","date":"2021-01-07","adj_close":142.47},
{"symbol":"PG","date":"2021-01-08","adj_close":138.79},
{"symbol":"HSY","date":"2021-01-08","adj_close":152.03},
{"symbol":"CLX","date":"2021-01-08","adj_close":197.84},
{"symbol":"COST","date":"2021-01-08","adj_close":369.94},
{"symbol":"MDLZ","date":"2021-01-08","adj_close":58.19},
{"symbol":"K","date":"2021-01-08","adj_close":60.2},
{"symbol":"KHC","date":"2021-01-08","adj_close":33.62},
{"symbol":"PEP","date":"2021-01-08","adj_close":144.18},
{"symbol":"PG","date":"2021-01-11","adj_close":137.85},
{"symbol":"HSY","date":"2021-01-11","adj_close":150.11},
{"symbol":"CLX","date":"2021-01-11","adj_close":193.73},
{"symbol":"COST","date":"2021-01-11","adj_close":364.01},
{"symbol":"MDLZ","date":"2021-01-11","adj_close":57.09},
{"symbol":"K","date":"2021-01-11","adj_close":59.37},
{"symbol":"KHC","date":"2021-01-11","adj_close":32.85},
{"symbol":"PEP","date":"2021-01-11","adj_close":142.09},
{"symbol":"PG","date":"2021-01-12","adj_close":137.05},
{"symbol":"HSY","date":"2021-01-12","adj_close":149.38},
{"symbol":"CLX","date":"2021-01-12","adj_close":194.24},
{"symbol":"COST","date":"2021-01-12","adj_close":364.2},
{"symbol":"MDLZ","date":"2021-01-12","adj_close":57.32},
{"symbol":"K","date":"2021-01-12","adj_close":58.56},
{"symbol":"KHC","date":"2021-01-12","adj_close":32.18},
{"symbol":"PEP","date":"2021-01-12","adj_close":141.43},
{"symbol":"PG","date":"2021-01-13","adj_close":137.26},
{"symbol":"HSY","date":"2021-01-13","adj_close":149.92},
{"symbol":"CLX","date":"2021-01-13","adj_close":193.74},
{"symbol":"COST","date":"2021-01-13","adj_close":366.95},
{"symbol":"MDLZ","date":"2021-01-13","adj_close":57.37},
{"symbol":"K","date":"2021-01-13","adj_close":59.14},
{"symbol":"KHC","date":"2021-01-13","adj_close":32.01},
{"symbol":"PEP","date":"2021-01-13","adj_close":142.59},
{"symbol":"PG","date":"2021-01-14","adj_close":135.8},
{"symbol":"HSY","date":"2021-01-14","adj_close":147.42},
{"symbol":"CLX","date":"2021-01-14","adj_close":195.55},
{"symbol":"COST","date":"2021-01-14","adj_close":362.35},
{"symbol":"MDLZ","date":"2021-01-14","adj_close":57.31},
{"symbol":"K","date":"2021-01-14","adj_close":59.05},
{"symbol":"KHC","date":"2021-01-14","adj_close":32.08},
{"symbol":"PEP","date":"2021-01-14","adj_close":141.76},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-19","adj_close":133.6},
{"symbol":"HSY","date":"2021-01-19","adj_close":148.75},
{"symbol":"CLX","date":"2021-01-19","adj_close":196.51},
{"symbol":"COST","date":"2021-01-19","adj_close":354.47},
{"symbol":"MDLZ","date":"2021-01-19","adj_close":57.14},
{"symbol":"K","date":"2021-01-19","adj_close":58.46},
{"symbol":"KHC","date":"2021-01-19","adj_close":32.36},
{"symbol":"PEP","date":"2021-01-19","adj_close":142.06},
{"symbol":"PG","date":"2021-01-20","adj_close":131.93},
{"symbol":"HSY","date":"2021-01-20","adj_close":149.63},
{"symbol":"CLX","date":"2021-01-20","adj_close":196.93},
{"symbol":"COST","date":"2021-01-20","adj_close":361.3},
{"symbol":"MDLZ","date":"2021-01-20","adj_close":57.1},
{"symbol":"K","date":"2021-01-20","adj_close":57.64},
{"symbol":"KHC","date":"2021-01-20","adj_close":32.86},
{"symbol":"PEP","date":"2021-01-20","adj_close":141.33},
{"symbol":"PG","date":"2021-01-21","adj_close":131.01},
{"symbol":"HSY","date":"2021-01-21","adj_close":148.98},
{"symbol":"CLX","date":"2021-01-21","adj_close":197.21},
{"symbol":"COST","date":"2021-01-21","adj_close":362.8},
{"symbol":"MDLZ","date":"2021-01-21","adj_close":56.12},
{"symbol":"K","date":"2021-01-21","adj_close":57.89},
{"symbol":"KHC","date":"2021-01-21","adj_close":32.78},
{"symbol":"PEP","date":"2021-01-21","adj_close":139.61},
{"symbol":"PG","date":"2021-01-22","adj_close":130},
{"symbol":"HSY","date":"2021-01-22","adj_close":148.2},
{"symbol":"CLX","date":"2021-01-22","adj_close":202.35},
{"symbol":"COST","date":"2021-01-22","adj_close":362.3},
{"symbol":"MDLZ","date":"2021-01-22","adj_close":56.25},
{"symbol":"K","date":"2021-01-22","adj_close":58.3},
{"symbol":"KHC","date":"2021-01-22","adj_close":32.91},
{"symbol":"PEP","date":"2021-01-22","adj_close":138.59},
{"symbol":"PG","date":"2021-01-25","adj_close":132.24},
{"symbol":"HSY","date":"2021-01-25","adj_close":147.53},
{"symbol":"CLX","date":"2021-01-25","adj_close":211.96},
{"symbol":"COST","date":"2021-01-25","adj_close":361.88},
{"symbol":"MDLZ","date":"2021-01-25","adj_close":56.87},
{"symbol":"K","date":"2021-01-25","adj_close":59.84},
{"symbol":"KHC","date":"2021-01-25","adj_close":33.75},
{"symbol":"PEP","date":"2021-01-25","adj_close":140.18},
{"symbol":"PG","date":"2021-01-26","adj_close":133.09},
{"symbol":"HSY","date":"2021-01-26","adj_close":149.52},
{"symbol":"CLX","date":"2021-01-26","adj_close":212.99},
{"symbol":"COST","date":"2021-01-26","adj_close":364.98},
{"symbol":"MDLZ","date":"2021-01-26","adj_close":57.59},
{"symbol":"K","date":"2021-01-26","adj_close":60.92},
{"symbol":"KHC","date":"2021-01-26","adj_close":34.39},
{"symbol":"PEP","date":"2021-01-26","adj_close":141.8},
{"symbol":"PG","date":"2021-01-27","adj_close":128.38},
{"symbol":"HSY","date":"2021-01-27","adj_close":146.19},
{"symbol":"CLX","date":"2021-01-27","adj_close":222.18},
{"symbol":"COST","date":"2021-01-27","adj_close":356.39},
{"symbol":"MDLZ","date":"2021-01-27","adj_close":56.42},
{"symbol":"K","date":"2021-01-27","adj_close":62.36},
{"symbol":"KHC","date":"2021-01-27","adj_close":34.74},
{"symbol":"PEP","date":"2021-01-27","adj_close":138.04},
{"symbol":"PG","date":"2021-01-28","adj_close":130.36},
{"symbol":"HSY","date":"2021-01-28","adj_close":148.21},
{"symbol":"CLX","date":"2021-01-28","adj_close":209.57},
{"symbol":"COST","date":"2021-01-28","adj_close":357.06},
{"symbol":"MDLZ","date":"2021-01-28","adj_close":57.12},
{"symbol":"K","date":"2021-01-28","adj_close":60.17},
{"symbol":"KHC","date":"2021-01-28","adj_close":33.96},
{"symbol":"PEP","date":"2021-01-28","adj_close":139.19},
{"symbol":"PG","date":"2021-01-29","adj_close":128.21},
{"symbol":"HSY","date":"2021-01-29","adj_close":145.44},
{"symbol":"CLX","date":"2021-01-29","adj_close":209.46},
{"symbol":"COST","date":"2021-01-29","adj_close":352.43},
{"symbol":"MDLZ","date":"2021-01-29","adj_close":55.44},
{"symbol":"K","date":"2021-01-29","adj_close":58.94},
{"symbol":"KHC","date":"2021-01-29","adj_close":33.51},
{"symbol":"PEP","date":"2021-01-29","adj_close":136.57},
{"symbol":"PG","date":"2021-02-01","adj_close":128.97},
{"symbol":"HSY","date":"2021-02-01","adj_close":145.11},
{"symbol":"CLX","date":"2021-02-01","adj_close":210.02},
{"symbol":"COST","date":"2021-02-01","adj_close":350.52},
{"symbol":"MDLZ","date":"2021-02-01","adj_close":55.25},
{"symbol":"K","date":"2021-02-01","adj_close":58.82},
{"symbol":"KHC","date":"2021-02-01","adj_close":33.25},
{"symbol":"PEP","date":"2021-02-01","adj_close":136.98},
{"symbol":"PG","date":"2021-02-02","adj_close":128.79},
{"symbol":"HSY","date":"2021-02-02","adj_close":147.12},
{"symbol":"CLX","date":"2021-02-02","adj_close":204.23},
{"symbol":"COST","date":"2021-02-02","adj_close":355.58},
{"symbol":"MDLZ","date":"2021-02-02","adj_close":56.16},
{"symbol":"K","date":"2021-02-02","adj_close":58.45},
{"symbol":"KHC","date":"2021-02-02","adj_close":33.16},
{"symbol":"PEP","date":"2021-02-02","adj_close":138.38},
{"symbol":"PG","date":"2021-02-03","adj_close":128.95},
{"symbol":"HSY","date":"2021-02-03","adj_close":146.58},
{"symbol":"CLX","date":"2021-02-03","adj_close":204.59},
{"symbol":"COST","date":"2021-02-03","adj_close":355.21},
{"symbol":"MDLZ","date":"2021-02-03","adj_close":55.28},
{"symbol":"K","date":"2021-02-03","adj_close":58.01},
{"symbol":"KHC","date":"2021-02-03","adj_close":33.01},
{"symbol":"PEP","date":"2021-02-03","adj_close":138.02},
{"symbol":"PG","date":"2021-02-04","adj_close":129.03},
{"symbol":"HSY","date":"2021-02-04","adj_close":147.22},
{"symbol":"CLX","date":"2021-02-04","adj_close":191.65},
{"symbol":"COST","date":"2021-02-04","adj_close":355.85},
{"symbol":"MDLZ","date":"2021-02-04","adj_close":56},
{"symbol":"K","date":"2021-02-04","adj_close":57.87},
{"symbol":"KHC","date":"2021-02-04","adj_close":32.92},
{"symbol":"PEP","date":"2021-02-04","adj_close":139.68},
{"symbol":"PG","date":"2021-02-05","adj_close":129.57},
{"symbol":"HSY","date":"2021-02-05","adj_close":146.6},
{"symbol":"CLX","date":"2021-02-05","adj_close":191.25},
{"symbol":"COST","date":"2021-02-05","adj_close":355.17},
{"symbol":"MDLZ","date":"2021-02-05","adj_close":56.21},
{"symbol":"K","date":"2021-02-05","adj_close":58.03},
{"symbol":"KHC","date":"2021-02-05","adj_close":33.8},
{"symbol":"PEP","date":"2021-02-05","adj_close":140.96},
{"symbol":"PG","date":"2021-02-08","adj_close":129.17},
{"symbol":"HSY","date":"2021-02-08","adj_close":149.33},
{"symbol":"CLX","date":"2021-02-08","adj_close":190},
{"symbol":"COST","date":"2021-02-08","adj_close":359.83},
{"symbol":"MDLZ","date":"2021-02-08","adj_close":56.02},
{"symbol":"K","date":"2021-02-08","adj_close":57.74},
{"symbol":"KHC","date":"2021-02-08","adj_close":33.91},
{"symbol":"PEP","date":"2021-02-08","adj_close":140.4},
{"symbol":"PG","date":"2021-02-09","adj_close":128.67},
{"symbol":"HSY","date":"2021-02-09","adj_close":149.62},
{"symbol":"CLX","date":"2021-02-09","adj_close":187.35},
{"symbol":"COST","date":"2021-02-09","adj_close":359.56},
{"symbol":"MDLZ","date":"2021-02-09","adj_close":55.5},
{"symbol":"PEP","date":"2021-02-09","adj_close":139.6},
{"symbol":"KHC","date":"2021-02-09","adj_close":33.71},
{"symbol":"K","date":"2021-02-09","adj_close":57.64}]
Here is a sample including company ticker selector:
Presentator.js:
export function Presentator() {
const [data, setData] = useState([]);
const [ticker, setTicker] = useState('');
useEffect(() => {
const fetchData = async () => {
/* DO ACTUAL FETCH FROM SERVICE */
const result = await Promise.resolve(response);
setData(result);
}
fetchData();
}, []);
const handleTickerChange = (event) => {
setTicker(event.target.value);
}
const getTickerData = (ticker) => {
return data.filter(item => item.symbol.toLowerCase() === ticker.toLowerCase());
};
const getTickerDropdownValues = () => {
const set = new Set();
data.forEach(item => {
if (!set.has(item.symbol)) {
set.add(item.symbol);
}
});
return Array.from(set);
}
const getTickerDropdown = () => {
const options = getTickerDropdownValues();
return (
<select value={ticker} onChange={handleTickerChange}>
{options.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
);
}
return (
<>
{getTickerDropdown()}
<Graph data={getTickerData(ticker)} />
</>
);
}
Graph.js:
export function Graph(props) {
const { data } = props;
const getChartData = () => {
const labels = [];
const series = [];
data.forEach(item => {
labels.push(item.date);
series.push(item.adj_close);
});
return {
labels: labels,
series: [series]
};
}
// Add your graph configuration here
const chartOptions = {
// width: 2000,
height: 400,
// scaleMinSpace: 20
};
return (
<ChartistGraph data={getChartData()} options={chartOptions} type="Line" />
);
}
Basically, the Presentator handles the initial fetching of the data and the logic to split the data by ticker. Then, the Graph component handles the visualization of the specific ticker data itself.
You can check a working example at this codesandbox.
You don't need to store anything more in the state than the data itself. In our case we're also storing the selected value for the ticker dropdown. Everything else can be calculated.
In the getChartData function you can do further filtering and manipulation of the data as for example presenting only the last 10 records(dates) instead of the whole set.
If I understand you correctly, you need to display the adj_close values for each date, grouped by symbol. Is that correct?
First, make changes to your state:
const [chartData, setChartData] = useState({
labels: [],
series: []
});
You can group the response by symbol like this:
const symbols = response.reduce((map, value) => {
if (map.has(value.symbol)) {
map.set(value.symbol, [...map.get(value.symbol), value]);
} else {
map.set(value.symbol, [value]);
}
return map;
}, new Map())
Then get the unique dates:
const dates = [...new Set(response.map(r => r.date))]; // note: it doesn't sort dates!
Then construct the series multi-dimensional array. For each symbol, you include the adj_close values for every date.
const series = Array.from(symbols).map(value => {
const valuesForSymbol = value[1];
return dates.map(date => {
const valueForDate = valuesForSymbol.find(v => v.date === date);
return valueForDate.adj_close;
});
});
Set the state:
setChartData({labels: dates, series });
And finally, display the chart like this:
<ChartistGraph data={chartData} options={options} type="Line" />
Full example here.
I have rewritten you code check if its work for your situation
import React, { useState, useEffect } from "react";
import ChartistGraph from 'react-chartist';
export default function Graph() {
const [data, setData] = useState({
chart: {
label: [],
series: []
},
dataBySymbols: {},
symbols: [],
select: "",
});
const getData = () => {
setTimeout(() => {
const _tmp = new Set();
const dataBySymbols = {};
response.forEach(item => {
_tmp.add(item.symbol);
if (!dataBySymbols.hasOwnProperty(item.symbol)) {
dataBySymbols[item.symbol] = {
label: [],
series: [
[]
]
};
}
dataBySymbols[item.symbol]['label'].push(item.date);
dataBySymbols[item.symbol]['series'][0].push(item.adj_close);
});
const copy = {...data};
copy['dataBySymbols'] = dataBySymbols;
copy['symbols'] = Array.from(_tmp);
copy['chart'] = dataBySymbols[copy['symbols'][0]];
setData(copy);
}, 3000)
}
useEffect(() => {
getData()
}, [])
function onSelectChange(evt) {
const copy = {...data};
copy['select'] = evt.target.value;
copy['chart'] = copy.dataBySymbols[evt.target.value]
setData(copy);
}
const options = {
width: 500,
height: 400
};
return (
<div>
<select value={data.select} onChange={onSelectChange}>
{data.symbols.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
<ChartistGraph data={data.chart} options={options} type="Line" />
</div>
);
};
export default function App() {
return (
<Graph />
);
}
Here working example

localeCompare array of objects sorting not working [duplicate]

This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 3 years ago.
My issue similar to this, but not the same.
I'm trying to sort an array of objects using localeCompare. It has no reason not to work, but it's not working. Somehow I'm doing something right./sigh/
This is how I fetch the data
const [data, setData] = useState([]);
const [isBusy, setBusy] = useState(true)
useEffect(() => {
console.log('I was run once');
async function fetchData() {
const url = `${
process.env.REACT_APP_API_BASE
}/api/v1/endpoint/`;
axios.get(url).then((response: any) => {
setBusy(false);
setData(response.data.results)
console.log(response.data.results);
});
}
fetchData();
}, [])
This is the sorting function
function onSort(event: any, sortKey: string) {
const newData = data;
newData.sort((a: any, b: any): any => {
a[sortKey].toString().localeCompare(b[sortKey]);
})
setData(newData);
}
A typical array of objects is like this
[
{
"avatar": "big",
"name": "Username",
},
{
"avatar": "small",
"name": "Rex",
},
{
"avatar": "medium",
"name": "Duh",
}
]
Then the table header has this
<th scope="col" className="text-center" onClick={e => onSort(e, 'name')}>Name</th>
Although the onSort() function runs without any errors, the objects don't get sorted as per the sortKey
Am I using the localeCompare wrongly? What can I do to make the above right?
Also, the setData, I believe should update the data and thus trigger a rebuild of the table, which seems to be happening, because if I pass in an empty array to the setData, the table blanks.
edit:
The HTML part
...
return (
<div>
<table className="table table-hover">
<thead>
<tr>
<th onClick={e => onSort(e, 'avatar')}>Avatar</th>
<th onClick={e => onSort(e, 'name')}>Name</th>
</thead>
<tbody>
{data && data.map((item: any, index: any) => {
return (
<tr key={index}>
<th>{{ item.avatar}}</th>
<td>{item.name}</td>
<td className="text-center" style={{ 'fontSize': '32px', 'color': '#981c1e' }}>0</td>
</tr>
)
})}
</tbody>
</table>
</div>
...
If I understand, if the setData triggers a data change, the render re-renders?
You need a return statement by using curly brackets in an arrow function
newData.sort((a: any, b: any): any => {
return a[sortKey].toString().localeCompare(b[sortKey]);
});

How can i add and remove a specific key of a object when using object.keys?

I'm doing a leaderboard for a game. The userInfo array that i am using contains fetched data from a json table. The array contains id, username, bestattempts and besttime along with the data from each category.
This table currently have 4 columns with and all the data from the json table is on table rows. I need to have the table not showing the "id" column, and instead showing a new "Rank" first column with a autoincrement row data [1,2,3,4,5] (Like on a leaderboard).
How can i make that happen with Object.keys working?
import React from "react";
import "./LeaderBoard.css";
const Head = ({keys, head}) => {
return (
<thead>
<tr>
{
keys.map(key =><th key={key}>{head[key] || key}</th> )
}
</tr>
</thead>
)
}
const Row = ({row}) => {
const keys = Object.keys(row)
return (
<tr key={row.id}>
{
keys.map(key => <td key={key}>{row[key]}</td>)
}
</tr> )
}
const LeaderBoard = ({usersInfo, head}) => {
const newArray = usersInfo.map(({ id, ...rest }, index) => ({ Rank: index + 1, ...rest }) )
newArray.sort(function sortByAttempts(a, b) {
return (a.bestattempts - b.bestattempts) && (a.besttime - b.besttime)
});
const keys = Object.keys(newArray[0])
return (
<div className="Leaderboard-wrapper">
<table>
<Head keys={keys} head={head}/>
<tbody>
{
newArray.map((row) => <Row row={row}/>)
}
</tbody>
</table></div>
)
};
export default LeaderBoard;

Convert string to JSON object for use in React.js style tag style={}

I am building a React.js application where I want to allow users to input styles in a text area which will affect the style of another element.
First, I have a row component which looks like this:
function Row(props) {
return (
<tr>
<td width="50%">
<textarea
style={{}}
value={props.style}
onChange={props.onStyleChange}>
</textarea>
</td>
<td><div className="">Row {props.id+1}</div></td>
</tr>
)
};
I am iterating through a list of rowData to populate my rows, which can be found here:
{this.state.rowData.map(function(row, index) {
return (
<Row
id={row.id}
style={row.style}
onStyleChange={function(e) {this.onStyleChange(e, row.id)}.bind(this)}/>
);
}.bind(this))}
Then in my onStyleChange function I have:
onStyleChange: function(e, id) {
this.state.rowData[id].style = e.target.value;
this.setState(this.state);
}
So as a user enters data into the the textarea, it adds to the i'th element in my rowData array. Assuming its the 0th row and the user enters "Hello" into the text area, then rowData[0].style = "Hello".
However, I would like to be able to do something like this: style={{props.style}} inside my Row component. But because it is currently a string it does not work. I have also tried style={JSON.parse(props.style)} which throws an error every time I add a new row because props.style='{}'. The error reads Uncaught SyntaxError: Unexpected token f in JSON at position 1
Always grateful for any help. There's got to be a much easier way to do this. Thank you.
Two steps to convert inline-style toobject-style` as restricted by React :
Parse the string to be a JSON object.
Convert the keys of this object to camel case (z-index becomes zIndex.. so on)
Congrats! i wrote the algorithm , check below :
const example1= "position:absolute;h-index:9001;"
const example2 = "-ms-transform: rotate(20deg);-webkit-transform: rotate(20deg);";
// 2ⁿᵈ step logic
const camelize = (string) => string.replace(/-([a-z])/gi,(s, group) => group.toUpperCase());
// 1ˢᵗ step logic which calls the 2ⁿᵈ step logic
const style2object = (style) => style.split(';').filter(s => s.length)
.reduce((a, b) => {
const keyValue = b.split(':');
a[camelize(keyValue[0])] = keyValue[1] ;
return a;
} ,{});
console.log("Example 1 : ", example1, '\n',
style2object(example1)
)
console.log("Example 2 : ", example2, '\n',
style2object(example2)
)
If it is helpful the style attribute needs an object like {"color": "blue"}
I made a demo with your code the only thing that escapes me is how to update with the onChange event.
function Row(props) {
const styleValue = JSON.stringify(props.style);
return (
<tr>
<td width="50%">
<textarea
style={props.style}
defaultValue={styleValue}
onChange={props.onStyleChange}/>
</td>
<td><div className="">Row {props.id+1}</div></td>
</tr>
)
};
class App extends React.Component {
state = {
rowData: [{
id: 1,
style: {
color: 'blue'
}
}, {
id: 2,
style: {
color: 'red',
backgroundColor:'#000'
}
}]
};
onStyleChange(e, id) {
const rows = this.state.rowData;
const row = rows.find(row => row.id === id);
const index = rows.indexOf(row);
rows[index]['style'] = JSON.parse(e.target.value);
this.setState({
rowData: rows
});
}
render() {
return (
<table>
<tbody>
{
this.state.rowData.map(function(row, index) {
return (
<Row
id={row.id}
key={index}
style={row.style}
onStyleChange={function(e) {this.onStyleChange(e, row.id)}.bind(this)}/>
);
}.bind(this))
}
</tbody>
</table>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
http://codepen.io/GGarciaSeco/pen/vgVEGX?editors=0010
You can take a look to the React documentation in the next link
https://facebook.github.io/react/docs/dom-elements.html#style

Categories