Reputation: 11
I'm trying to figure out how to put multiple data to a radar chart using map function. I picked some related codes as down below.
class TopPage_Comp extends Component{
constructor(props){
super(props)
this.state = {
motivationtypeTestRecords: []
}
}
componentDidMount() {
const id = this.state.user.id
fetch("http://localhost:8080/test/" + id, {
method: "GET"
})
.then((response) => {
response.json().
then(json => {
const types = json.motivationtypeList
this.setState(
{
motivationtypeTestRecords: records,
}
)
})
})
}
render() {
const backgroundColors = [
'rgba(255,99,71,0.35)',
'rgba(0,128,0,0.35)',
'rgba(255,255,0,0.35)'
];
const borderColors = [
'rgba(255,99,71,1)',
'rgba(0,128,0,1)',
'rgba(255,255,0,1)'
];
return(
<>
{this.state.motivationtypeTestRecords.length > 0 &&
<MotivationtypeChart
scores={this.state.motivationtypeTestRecords}
backgroundColors={backgroundColors}
borderColors={borderColors}
/>
}
</>
)
}
}
export class MotivationtypeChart extends Component {
constructor(props){
super(props);
}
render(){
return(
<Radar
data={{
labels: ['Drive', 'Volunteer', 'Create', 'Analyze'],
datasets:[
{this.props.scores.map((s, index) =>
{
label: s.createdDate,
data: [
s.driveScore,
s.volunteerScore,
s.createScore,
s.analyzeScore
],
backgroundColor: this.props.backgroundColors[index],
borderColor: this.props.borderColor[index],
borderWidth: 2
},
)}
]
}}
height={400}
width={500}
options={{
maintainAspectRation: false,
scale: {
grid: {
display: false
},
beginAtZero: true,
min: 0,
max: 20,
stepSize: 1,
}
}}
/>
)
}
}
I'm using react-chartjs-2. The error repeatedly says unexpected keyword 'this' when it calls this.props.scores on MotivationtypeChart component. Is it not allowed to use map function inside datasets array at the first place? Or is there any way to solve this problem? I would really appreciate advices from skilled programmer like people on here.
Upvotes: 0
Views: 1238
Reputation: 2635
I think you are using map directly in array so that's why it's showing you error plus it's not good way to create data in like this.
So instead try to create new function which will return data and then use that functions return as dataSets
in Radar
chart
export class MotivationtypeChart extends Component {
constructor(props){
super(props);
}
const getRadarData = () => {
return this.props.scores.map((s, index) => {
return {
label: s.createdDate,
data: [s.driveScore, s.volunteerScore, s.createScore, s.analyzeScore],
backgroundColor: this.props.backgroundColors[index],
borderColor: this.props.borderColor[index],
borderWidth: 2
};
});
};
render(){
return(
<Radar
data={{
labels: ['Drive', 'Volunteer', 'Create', 'Analyze'],
datasets:[...getRadarData()]
}}
height={400}
width={500}
options={{
maintainAspectRation: false,
scale: {
grid: {
display: false
},
beginAtZero: true,
min: 0,
max: 20,
stepSize: 1,
}
}}
/>
)
}
}
Upvotes: 1