I would like to display a number of the component Star (MUI component) based on the number of points the user has earned (this.state.points
).
I don't know how to do this.
import React, { Component } from "react";
import { Star } from "@material-ui/icons";
Points extends Component {
constructor(props) {
super(props);
this.state = {
points: 6
};
}
render() {
return (
<div>
<p>
+ {this.state.points} points
<Star />
</p>
</div>
);
}
}
export default Points;
Dynamic component rendering with React To allow us to render a JSON by dynamic components using their name we first have to loop through the array of components itself. Below you can see that we're using the map function to do exactly that.
React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components. Prerequisites: The pre-requisites for this project are: React Knowledge.
Editor's note: This tutorial was last updated on 16 June 2022 to reflect changes made in React v18. JSX is a powerful extension to JavaScript that allows us to define UI components.
To render the components based on the component key in the JSON config, we first need to create an object that maps the components with the component key. As you can see, I have mapped the component key with the corresponding Reactstrap component. At the top, we will import all the required components.
You can use Array.fill
to create new Array with this.state.points
number of empty slots which you then fill with the <Star />
component like so:
import React, { Component } from "react";
import { Star } from "@material-ui/icons";
class Points extends Component {
constructor(props) {
super(props);
this.state = {
points: 6
};
}
render() {
return (
<div>
<p>
+ {this.state.points} points
// This is where the magic happens
{Array(this.state.points).fill(<Star />)}
</p>
</div>
);
}
}
export default Points;
Here is a working Sandbox : https://codesandbox.io/s/vj3xpyn0x0
Try this
import React, { Component } from "react";
import { Star } from "@material-ui/icons";
Points extends Component {
constructor(props) {
super(props);
this.state = {
points: 6
};
}
render() {
return (
<div>
<p>
+ {this.state.points} points
{Array.from(Array(this.state.points)).map((x, index) => <Star key={index} />)}
</p>
</div>
);
}
}
export default Points;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With