How do I change state from a map loop? - reactjs

I created a "skillProg" state using useState and want to change it using the "setSkillProg" inside a map loop. But I get a unexpected token error. Here is the code:
const Skills = () => {
const skills = [
{ bgcolor: "#0bd30e", completed: 100, name: "HTML" },
{ bgcolor: "#0bd30e", completed: 100, name: "CSS" },
{ bgcolor: "#0bd30e", completed: 90, name: "JavaScript" },
{ bgcolor: "#0bd30e", completed: 90, name: "React" },
{ bgcolor: "#0bd30e", completed: 90, name: "Express" },
{ bgcolor: "#0bd30e", completed: 90, name: "MongoDB" },
{ bgcolor: "#0bd30e", completed: 90, name: "Firebase" },
{ bgcolor: "#0bd30e", completed: 90, name: "PostGreSQL" },
{ bgcolor: "#0bd30e", completed: 90, name: "Git" },
{ bgcolor: "#0bd30e", completed: 90, name: "JavaScript" },
];
const [skillProg, setSkillProg] = useState(0);
return (
<div className="skills">
{skills.map((skill, idx) => (
{setSkillProg({skill.completed})}
<ProgressBar
key={idx}
bgcolor={skill.bgcolor}
completed={skillProg}
name={skill.name}
className="progress_bar"
/>
))}
</div>
);
};
export default Skills;

When working with JSX elements in ReactJS, you typically return these values when working in map() (as well as when working within render()). Try this...
return(
<ProgressBar
key={idx}
bgcolor={skill.bgcolor}
completed={skillProg}
name={skill.name}
className="progress_bar"
/>
);
Take a look at the default syntax from MDN Web Docs, you'll see the return() there, too...
let newArray = arr.map(callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
}[, thisArg]);
Even though it's not JSX or ReactJS, it's still returning something.
P.S. I have asked for further debugging details, I will update my answer as needed when I get these.

Related

Create the Mixed Chart in react

I want to create the chart mixed chart with line and bar like the below image.
You firstly, import line from the chartjs-2 library. After add two dataset, and indicate one of them is bar chart. type:'bar' .
if you want to add two sides titles, you have to add yAxisID on the datasets. After this, you can put y and y1 axis on the options inside of the scales. Then add titles name in there. Please examine the codes.
Check the result of code:
import React from 'react'
import { Line } from "react-chartjs-2";
function MainChart() {
return (
<>
<Line
data={{
labels: ["1","2", "3", "4", "5"],
datasets: [
{
label: "Line value",
data: [1,2,3,4,5],
borderColor: `rgba(255,200,100, 0.1)`,
backgroundColor: `rgba(255,200,100,0.5)`,
yAxisID: 'y',
},
{
type: 'bar',
label: "bar value",
data: [1,2,3,4,5],
yAxisID: 'y1',
borderColor:"rgb(120, 80, 0, 0.8)",
backgroundColor: "rgb(50, 216, 190, 0.3)",
}
],
}}
options={{
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
ticks: {
color: "rgba(0, 0, 0, 1)",
},
grid: {
drawBorder: true,
drawTicks: true,
color: "rgba(0, 0, 0, 0.2)",
},
title: {
display: true,
text: "Line Title",
font: {
size: 17
},
},
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: "Bar Title",
font: {
size: 15
},
},
},
},
}}
/>
</>
)
}
export default MainChart
USE APEXCHARTS. I tried literally everything and apexcharts was the easiest of all the charts for reactjs. LMK if you have anymore questions!
https://apexcharts.com/react-chart-demos/mixed-charts/line-column/#
NOTE: the doc doesn't mention it but you want to import ReactApexCharts from the library like below.
you're gonna need to convert the class states into functional component states in react which shouldn't be too hard if you know basic React. Here's what your inside code should similarly look like:
import React, { useState } from "react";
import ReactApexChart from "react-apexcharts";
export default function Graph(props) {
const [options, setOptions] = useState({
chart: {
height: 350,
type: "line",
},
stroke: {
width: [0, 4],
},
dataLabels: {
enabled: true,
enabledOnSeries: [1],
},
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
// xaxis: { DONT NEED THIS, but if you check out the docs they have some useful stuff.
// type: 'datetime'
// },
yaxis: [
{
title: {
text: "Total Number of Sessions",
},
},
{
opposite: true,
title: {
text: "Total Traffic (Gbps)",
},
},
],
});
const [series, setSeries] = useState([
{
name: "Total Number of Sessions",
type: "column",
data: [440, 505, 414, 671, 227]//your data goes here
},
{
name: "Total Traffic (Gbps)",
type: "line",
data: [40, 50, 41, 67, 22]//your data goes here
},
]);
return (
<>
<ReactApexChart
options={options}
series={series}
type='line'
height={350}
/>
</>
);
}

How to display different data if a switch is toggled in React-Native

I'm trying to make a donut chart that shows different values. But if the switch on the screen it toggled, I want it to display a different set of values.
All the data is currently stored in an array I called data.
Donut chart package I'm using
I tried solving this problem with an if-statement to check if the toggle is enabled and changed the values of the data array accordingly. However, when I try this, I get the error "data" is read-only when I switch the toggle on.
See relevant code:
import { React, useState } from "react";
import { Switch } from "react-native";
import { DonutChart } from "react-native-circular-chart";
const ResultScreen = ({ navigation }) => {
const [isEnabled, setIsEnabled] = useState(false);
const data = [
{ name: "Privacy", value: 30, color: "blue" },
{ name: "Integriteit", value: 20, color: "green" },
{ name: "Collegialiteit", value: 15, color: "pink" },
{ name: "Slaap", value: 35, color: "red" },
];
const toggleSwitch = () => {
if (isEnabled) {
data = [
{ name: "Privacy", value: 30, color: "blue" },
{ name: "Integriteit", value: 20, color: "green" },
{ name: "Collegialiteit", value: 15, color: "pink" },
{ name: "Slaap", value: 35, color: "red" },
];
} else {
data = [
{ name: "Honor", value: 50, color: "blue" },
{ name: "Usage 2", value: 10, color: "green" },
{ name: "Usage 3", value: 10, color: "pink" },
{ name: "Usage 4", value: 30, color: "red" },
];
}
setIsEnabled((previousState) => !previousState);
};
return (
<DonutChart
data={data}
strokeWidth={15}
radius={100}
containerWidth={500}
containerHeight={500}
type="butt"
startAngle={0}
endAngle={360}
animationType="slide"
/>
);
};
export default ResultScreen;
Feel free to reach out if you need any more context!
You have a few options here, the quickest one given your code would be to add ternary check in your data prop of the chart, so when you change the toggle state, it will display different data. It would look like this
const enabledData = [
{ name: "Privacy", value: 30, color: "blue" },
{ name: "Integriteit", value: 20, color: "green" },
{ name: "Collegialiteit", value: 15, color: "pink" },
{ name: "Slaap", value: 35, color: "red" },
];
const disabledData = [
{ name: "Honor", value: 50, color: "blue" },
{ name: "Usage 2", value: 10, color: "green" },
{ name: "Usage 3", value: 10, color: "pink" },
{ name: "Usage 4", value: 30, color: "red" },
];
const toggleSwitch = () => {
setIsEnabled(!isEnabled);
};
return (
<DonutChart
data={isEnabled ? enabledData : disabledData}
strokeWidth={15}
radius={100}
containerWidth={500}
containerHeight={500}
type="butt"
startAngle={0}
endAngle={360}
animationType="slide"
/>
);
This should do the job for you, however I think you should look into optimising this logic/component if you are building something scalable.
Your data is a const try declaring it using let.
eg let data = []

Struggling to correctly update and re-render chart on react-chartjs-2

I am building an app for gym-goers to record and track their progress. For each exercise they input, it should render a chart showing their previous track record. This is working fine.
Users can then add another entry to this track record, but it does not update the chart unless you refresh the page. I can't work out why or how to fix it.
There are a number of different components involved - a parent Exercise.js one, then an ExerciseFooter.js one, which contains the buttons to adjust the target or add a new entry to the exercise, and then AddHistory.js and SetTarget.js components which contain modals and the logic to update the exercise via Redux and MongoDB.
A minimal version of the Exercise.js page is here (I've collapsed the stuff that's mainly styling into single lines as much as possible):
import React, { useState, useEffect } from "react";
import { ExerciseFooter } from "./ExerciseFooter";
import { Line } from "react-chartjs-2";
import { useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
export const Exercise = (props) => {
const location = useLocation();
const users = useSelector((state) => state.auth);
const localUser = JSON.parse(localStorage.getItem("profile"));
const [user, setUser] = useState("");
const [exerciseProp, setExerciseProp] = useState({
history: [""],
target: 0,
});
useEffect(() => {
localUser &&
localUser?.result &&
users.length > 0 &&
setUser(
users.filter(
(filteredUser) => filteredUser._id == props.match.params.userId
)[0]
);
if (!localUser) setUser("");
setExerciseProp(
user?.exercises?.filter(
(exercise) => exercise._id == props.match.params.exerciseId
)[0]
);
}, [users, location]);
//styling for chart
const [barData, setBarData] = useState({
labels: [""],
datasets: [
{ label: "Target", fill: false, radius: 0, data: [""], borderColor: ["rgba(35, 53, 89)"], borderWidth: [3], },
{ label: "You did", data: [""], tension: 0.3, borderColor: ["white"], backgroundColor: ["white"], borderWidth: 3, },
],
});
//updating chart data
var weightArr = [];
var dateArr = [];
var targetArr = [];
if (exerciseProp) {
exerciseProp.history.map((hist) =>
weightArr.push(parseInt(hist.weight) || 0)
);
exerciseProp.history.map((hist) => dateArr.push(hist.date));
for (let i = 0; i < exerciseProp.history.length; i++) {
targetArr.push(exerciseProp.target);
}
}
useEffect(() => {
if (exerciseProp) {
setBarData({
labels: dateArr,
datasets: [
{
label: "Target",
fill: false,
radius: 0,
data: targetArr,
borderColor: ["rgba(35, 53, 89)"], borderWidth: [3],
},
{
label: "Weight",
data: weightArr,
tension: 0.3, borderColor: ["white"], backgroundColor: ["white"], borderWidth: 3,
},
],
});
}
}, [users]);
//render chart ones exerciseProp is populated
if (exerciseProp) {
return (
<div style={{ marginTop: "200px" }}>
<Line
data={barData}
options={{ plugins: { title: { display: false, }, legend: { display: false, }, },
scales: { x: { grid: { color: "white", font: { family: "Dongle", size: 20, }, }, ticks: { color: "white", font: { family: "Dongle", size: 20, }, }, }, y: { grid: { color: "white", }, ticks: { color: "white", font: { family: "Dongle", size: 20, }, }, }, }, }}
/>
{exerciseProp && <ExerciseFooter user={user} exercise={exerciseProp} />}
</div>
);
} else {
return <>Loading...</>;
}
};
I've tried doing a few different things but nothing has worked. I tried adding an 'update' state variable which was updated by a function passed down to the the various dispatches, and then added it to the dependencies of the useEffects, but that didn't seem to make any difference.
Any help much appreciated! As I say, if I just force a refresh then it works fine but know that's bad practice so trying to work out why it isn't re-rendering correctly.
Thanks!
You just have to enable redraw prop
like this
<Line
redraw={true}
data={barData}
options={{ plugins: { title: { display: false, }, legend: { display: false, }, },
scales: { x: { grid: { color: "white", font: { family: "Dongle", size: 20, }, }, ticks: { color: "white", font: { family: "Dongle", size: 20, }, }, }, y: { grid: { color: "white", }, ticks: { color: "white", font: { family: "Dongle", size: 20, }, }, }, }, }}/>
this all you have to do
redraw={true}

react-graph-vis - Grapg is not re rendering even ofter state changes

When I try to update the state on the hover event, the actual state value is getting changed but the graph is not re-rendering.
in the console, I am able to see the node label is changed to sample. but the graph is not rerendering.
Here is my react function based component.
import React, { useEffect, useState } from 'react';
import Graph from 'react-graph-vis';
import './vis-network.css';
function RelationGraph1() {
const [graph, setGraph] = useState({
nodes: [
{
id: 1,
label: 'Node 1',
title: '',
},
{ id: 2, label: 'Node 2', title: '' },
{ id: 3, label: 'Node 3', title: '' },
{ id: 4, label: 'Node 4', title: '' },
{ id: 5, label: 'Node 5', title: '' },
],
edges: [
{ from: 1, to: 2 },
{ from: 1, to: 3 },
{ from: 2, to: 4 },
{ from: 2, to: 5 },
],
});
const options = {
layout: {
hierarchical: false,
},
edges: {
color: '#1D1D1D',
},
interaction: {
hover: true,
navigationButtons: true,
tooltipDelay: 0,
},
nodes: {
borderWidth: 0,
borderWidthSelected: 0,
color: '#0262C4',
shape: 'circle',
size: 1,
shadow: {
enabled: true,
color: 'rgba(0,0,0,0.5)',
size: 10,
x: 5,
y: 5,
},
font: {
color: '#fff',
size: 13,
bold: {
mod: 'bold',
},
},
},
};
const events = {
select: function (event) {
var { nodes, edges } = event;
console.log('Selected nodes:');
console.log(nodes);
console.log('Selected edges:');
console.log(edges);
},
showPopup: (id) => { // node id
const data = graph.nodes.map((el) => {
if (el.id === id) {
el.label = `sample node name`;
}
return el;
});
setGraph({ ...graph, nodes: data });
},
};
return (
<Graph
graph={graph}
options={options}
events={events}
style={{ height: '450px' }}
/>
);
}
export default RelationGraph1;
Really Appriciate for the help. Thanks !
I was able to update the label in hoverNode event like this:
hoverNode: (e) => {
const data = graph.nodes.map((el) => {
if (el.id === e.node) return { ...el, label: "sample node name" };
else return el;
});
const temp = { ...graph };
temp.nodes = data;
setGraph(temp);
},
Sample: https://codesandbox.io/s/long-bird-4h444?file=/src/App.js:1235-1501

React component only rendering one item in my object

So I have a react component set up to map through all the items in my array to display them on the page. I'm importing my component onto my homepage and passing the object as a prop from the imported component. However, when I load the page, only one item from the object is being rendered. I'm not entirely sure if I'm passing my object correctly. Any help would be appreciated! Code is below.
This is my Modal component. I'm mapping through the listGroupArray that has a spread operator with my data that is being passed from the home page.
export default function ModalButton({ setData, title, arrayData, dataTitle }) {
const [show, setShow] = useState(false);
const [button, setButton] = useState("Choose...")
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const listGroupArray = [{...arrayData}]
const changeButton = e => setButton(e)
return (
<>
<h5 className="inputFont text-center">{title}</h5>
<Button style={{ backgroundColor: "black", opacity: "1", color: "white", borderColor: "red" }} variant="primary" className="w-100 mb-4 inputFont" onClick={handleShow}>
{button}
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton className="modal-bg inputFont">
{dataTitle}
</Modal.Header>
<Modal.Body className="modal-bg">
<ListGroup>
{listGroupArray.map(item => (
<ListGroup.Item key={item.id} className="modal-bg">
<Button
style={{
backgroundColor: "black",
opacity: ".8",
color: "white",
borderColor: "red",
}}
className="inputFont w-100"
name={item.name}
value={item.value}
onClick={(e) => {
setData(item.value);
changeButton(item.name);
handleClose();
}}
>
{item.name}
</Button>
</ListGroup.Item>
))}
</ListGroup>
</Modal.Body>
</Modal>
</>
);
}
This is my homepage where I'm passing the array data as an object. I'm pretty sure this is where I'm going wrong. When I load the page, the component should render all the data in the object, however it's only rendering the last data, Classics.
<Modal title="Genre"
dataTitle="Pick A Genre"
setData={setGenrelist}
arrayData={
{
id: 1,
name: "Action and Adventure",
value: "10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584"
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635"
},
{
id: 3,
name: "Sci-Fi",
value: "1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491"
},
{
id: 4,
name: "Fantasy",
value: "9744"
},
{ id: 5,
name: "Thrillers",
value: "10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972"
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424"
},
{
id: 7,
name: "Children and Family",
value: "10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783"
},
{
id: 8,
name: "Comedies",
value: "1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736"
},
{
id: 9,
name: "Documentaries",
value: "10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875"
},
{
id: 10,
name: "Dramas",
value: "11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763"
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327"
},
{
id: 12,
name: "Horror",
value: "10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585"
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675"
},
{
id: 14,
name: "Classics",
value: "10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186"
}
}
/>
screenshot of the homepage
This image shows the component only rendering one data item which is Classics. Any advice on how to get all data rendered would be greatly appreciated! Thanks!
The error is in how you referenced the arrayData and the problematic curly brackets you used on an array. In your JSX code, you have a syntax error, you are supposed to enclose arrays in curly brackets, or better still just separate them to their own variable.
Your JSX should then look something like this:
function JSX(props) {
const arrayData = [
{
id: 1,
name: "Action and Adventure",
value:
"10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584",
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635",
},
{
id: 3,
name: "Sci-Fi",
value:
"1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491",
},
{
id: 4,
name: "Fantasy",
value: "9744",
},
{
id: 5,
name: "Thrillers",
value:
"10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972",
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424",
},
{
id: 7,
name: "Children and Family",
value:
"10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783",
},
{
id: 8,
name: "Comedies",
value:
"1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736",
},
{
id: 9,
name: "Documentaries",
value:
"10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875",
},
{
id: 10,
name: "Dramas",
value:
"11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763",
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327",
},
{
id: 12,
name: "Horror",
value:
"10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585",
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675",
},
{
id: 14,
name: "Classics",
value:
"10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186",
},
];
return (
<Modal
title="Genre"
dataTitle="Pick A Genre"
setData={(data) => console.log(data)}
arrayData={arrayData}
/>
);
}
The next bug you had was in using the spread operator. While arrays are technically objects in JavaScript they can't be spread with curly braces. This [{...arrayData}] is syntactically incorrect. Instead it should be [...arrayData]. With these in place, your code should run correctly.
I made a sandbox of your code in a working state for reference, check it out here:
https://codesandbox.io/s/young-snowflake-efqwk?file=/src/ModalButton.js:877-883

Resources