Recharts - How to fix graph scaling issue? - reactjs

In React application (using Next.js), I am trying to implement graph feature using recharts http://recharts.org/en-US/api/LineChart. My code is as below,
/index.js
const formatDate = (value) => {
return moment.unix(value).format('HH:MM A DD MM, YYYY')
}
const weeklyData = [
{ date: formatDate(1613619000), price: '1200.00' },
{ date: formatDate(1613617200), price: '1300.83' },
{ date: formatDate(1613615400), price: '1250.23' },
{ date: formatDate(1613611800), price: '500.55' },
{ date: formatDate(1613608200), price: '1600.23' },
{ date: formatDate(1613606400), price: '1850.93' },
{ date: formatDate(1613604600), price: '1750.23' },
{ date: formatDate(1613599200), price: '650.23' },
]
<LineChart
width={900}
height={250}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<Tooltip content={<CustomTooltip />} cursor={false} />
<Line type="monotone" dataKey="price" stroke="#4ec6f4" label="Shruthi" />
</LineChart>
/tooltip.js
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div className="tooltip">
<p className="tooltipLabel">{`$${payload[0].payload?.price}`}</p>
<p className="tooltipDesc">{`${payload[0]?.payload?.date}`}</p>
</div>
)
}
return null
}
CustomTooltip.propTypes = {
type: PropTypes.string,
payload: PropTypes.array,
label: PropTypes.string,
}
export default CustomTooltip
Right now YAxis is restricted to 1000 and graph(scaling) is displaying out of the box and its invisible.
Graph should be display within the container which I have set.
Here price is not fixed, it can be like 123456.88 or more than this.
In all scenario, how can I fix this issue?

try to convert price type to number or use values without single quotes.
Note: if possible, Post complete code for better response

Related

line 14 Expected an assignment or function call and instead saw an expression error

I'm am trying to map over seeded data, and I'm getting this error. Does anyone know why? Right now I am only trying to get the key of name to display, but I'm getting an expected an assignment or functionn error.
import { Link } from "react-router-dom";
import {getData} from "../Data"
export default function Home() {
let data = getData();
return (
<div>
{data.map((data) => {
{data.name}
})}
</div>
)
}
This is my seed data that I am trying to pull from.
I have imported it in my home.jsx file and called the function before my return statement.
let data = [
{
name: 'forgive-me-pleases',
image: 'https://i.imgur.com/0UCzcZM.jpg',
price: 50,
tags: ['pink', 'roses', 'bouquet', 'apologies'],
},
{
name: 'pink perfection',
image: 'https://i.imgur.com/XoEClf7.png',
price: 15,
tags: ['pink', 'gerbera daisy', 'singular', 'decor'],
},
{
name: 'hopeful sunshine',
image: 'https://i.imgur.com/LRrcBtN.png',
price: 30,
tags: ['yellow', 'sunflower', 'multiple', 'garden'],
},
{
name: 'motivational mug',
image: 'https://i.imgur.com/NOJ2ikN.png',
price: 25,
tags: ['yellow', 'gerbera daisy', 'singular (with mug)'],
},
{
name: 'breathtaking bouquet',
image: 'https://i.imgur.com/TuuKiHt.png',
price: 40,
tags: ['white', "baby's breath", 'bouquet', 'decor'],
},
{
name: 'loves-me-loves-me-knots',
image: 'https://i.imgur.com/SaTbTEx.png',
price: 20,
tags: ['mixed', 'gerbera daisy', 'mini bouguet', 'for fun'],
},
{
name: 'hiya, spring',
image: 'https://i.imgur.com/dJvHolr.jpg',
price: 35,
tags: ['mixed', 'hyacinths', 'bouquet', 'garden'],
},
{
name: 'can of compassion',
image: 'https://i.imgur.com/PN3jmrf.png',
price: 55,
tags: ['mixed', 'decor', 'bouquet (with can)', 'love'],
},
{
name: 'basket of beauty',
image: 'https://i.imgur.com/Z86X3qq.png',
price: 50,
tags: ['mixed', 'bouquet (with basket)', 'love', 'decor'],
},
];
export function getData() {
return data
}
Please change your code like below
let data = getData();
return (
<div>
{data.map((data) => {
<div>{data.name}</div>
})}
</div>
)

Use date on x-axis but id to set domain using recharts

I want to set the domain for the giving data set. So you can only see 5 objects at once. When doing this using ids it works well. However the x-axis uses dates. Is there a way to decouple the x-axis labels from the domain?
const initialData = [
{ id: 1, date: "05/16/2022", value: 4456 },
{ id: 2, date: "05/17/2022", value: 2789 },
{ id: 3, date: "05/18/2022", value: 7891 },
{ id: 4, date: "05/19/2022", value: 4561 },
{ id: 5, date: "05/20/2022", value: 5561 },
{ id: 6, date: "05/21/2022", value: 6561 },
{ id: 7, date: "05/22/2022", value: 4561 },
{ id: 8, date: "05/23/2022", value: 4561 },
{ id: 9, date: "05/24/2022", value: 4861 },
{ id: 10, date: "05/25/2022", value: 8561 },
{ id: 11, date: "05/26/2022", value: 6561 },
{ id: 12, date: "05/27/2022", value: 4561 }
];
const initialState = {
data: initialData,
left: initialData[0].date,
right: initialData[5].date,
refAreaLeft: undefined,
refAreaRight: undefined,
top: "dataMax+1000",
bottom: "dataMin-1000",
animation: true
};
<ResponsiveContainer width="100%" height={400}>
<LineChart
width={800}
height={400}
data={data}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
allowDataOverflow
dataKey="date"
domain={[left, right]}
type="category"
/>
<YAxis allowDataOverflow domain={[bottom, top]} type="number" />
<Tooltip />
<Line
type="natural"
dataKey="value"
stroke="#8884d8"
animationDuration={300}
/>
</LineChart>
</ResponsiveContainer>

How do I change state from a map loop?

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.

Managing with objects inside of array React state

I am trying to manage objects inside of an array. So I have array item which has some objects.
state = {
item: [
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
],
loader: true
};
I added a method which changes the image on click, but it changes the image in all objects
likedBtn = () => {
this.setState((prevState) => ({
item: prevState.item.map(
obj => (obj.heart === heart ? Object.assign(obj, {heart: heartRed}): obj)
)
}));
console.log('liked');
}
How can I assign that method to prevent acting on all the objects inside of an array?
<ProductsItems liked={this.likedBtn} addToCart={this.clickHandler} cls={item.cls} img={item.img} productName={item.productName} price={item.price} heart={item.heart} />
Sorry for such a dumb explanation but I hope you'll understand it. The heart is blue and it is red when clicked. That is all that I need but when I click only the one heart, all others change as well
This would do it
state = {
item: [
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
],
loader: true
};
render(){
<div>
{this.state.item.map( (obj,index) => {
<div
key={index}
onClick={() => this.handleClick(index)}
liked={this.likedBtn}
cls={obj.cls}
img={obj.img}
productName={obj.productName}
price={obj.price}
heart={obj.heart}
>
</div>
})}
</div>
}
handleClick = index => {
this.setState( prevState => (prevState.item[index].heart = heartRed, prevState)
}

How to load data dynamically with recharts correctly?

Problem:
I am creating a react application. There I am using recharts to draw a bar chart. But It is not drawing for the data set which is dynamically loaded.
My code is like this.
import React from "react";
import {
BarChart,
Bar,
Cell,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from "recharts";
let data = [];
let item;
const data1 = [
{
id: 'Page A', count: 2400,
},
{
id: 'Page B', count: 2210,
},
{
id: 'Page C', count: 2290,
},
{
id: 'Page D', count: 2000,
},
{
id: 'Page E', count: 2181,
},
{
id: 'Page F', count: 2500,
},
{
id: 'Page G', count: 2100,
},
];
const addItemToData = (el) => {
item = {
id: el.id,
count: 2,
};
data.push(item);
};
const OffenceStatusChart = ({ offences }) => {
if (Object.keys(offences) !== 0) {
Object.values(offences).map((el, index) =>
addItemToData(Object.values(el)[1])
);
}
if (data1) {
console.log(data1);
console.log(data)
}
return (
<React.Fragment>
{data? (<BarChart
width={800}
height={300}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="id" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="count" fill="#8884d8" />
</BarChart>):null}
</React.Fragment>
);
};
export default OffenceStatusChart;
In here data1 array data set is working correctly but for data array data set it showing the chart as like this.
when I hover over the graph it shows like this.
In the inspect window is showing like this.
the data array is like this.
the data1 array is like this.
Both arrays are in same format but for the data array it is not drawing the bar char but for data1 array. I tried to realize so much what is this error but I was completely helpless so that is why I asked it here. So if someone can help me to solve this issue it really really grateful. Thank you

Resources