Reputation: 2191
I'm new to React so this may be simple to fix, but I cannot access {this.props.AvgRating} in the ReviewsTotalStars.js file. I'm having to use the following state code to access a variable called ratingStars
:
this.state = {
ratingStars: 3.5
};
But I don't want to use the above ratingStars, and would instead prefer to use the props.AvgRating. Why cannot I access it? Here is my simple code:
index.js:
import React, { Component } from "react";
import { render } from "react-dom";
import ReviewsLeftArea from "./ReviewsLeftArea";
import "./style.css";
const avgRating = 3.5;
class App extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return (
<div>
<ReviewsLeftArea AvgRating={avgRating} />
</div>
);
}
}
render(<App />, document.getElementById("root"));
ReviewsLeftArea.js:
import React from "react";
import ReviewsTotalStars from "./ReviewsTotalStars";
export default class ReviewsLeftArea extends React.Component {
render() {
return (
<div>
<ReviewsTotalStars avgRating={this.props.AvgRating} />
</div>
);
}
}
ReviewsTotalStars.js:
import React from "react";
export default class ReviewsTotalStars extends React.Component {
constructor() {
super();
this.state = {
ratingStars: 3.5
};
}
render() {
return (
<div>
{this.state.ratingStars} works but this {this.props.AvgRating} doesn't
</div>
);
}
}
Thanks for any help and explanations here.
Upvotes: 0
Views: 27
Reputation: 1042
Should be simple to fix, in react, you should never create vaiables outside of the class you are working on, instead you should add them to the state object, like this:
Index.js:
import React, { Component } from "react";
import { render } from "react-dom";
import ReviewsLeftArea from "./ReviewsLeftArea";
import "./style.css";
// const avgRating = 3.5;
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
avgRating: 3.5;
};
}
render() {
return (
<div>
<ReviewsLeftArea AvgRating={this.state.avgRating} />
</div>
);
}
}
render(<App />, document.getElementById("root"));
ReviewsTotalStars.js:
import React from "react";
export default class ReviewsTotalStars extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div>
{this.props.avgRating} //now this should work
</div>
);
}
}
Upvotes: 0
Reputation: 3274
In ReviewsTotalStars you want to access:
this.props.AvgRating
But it is actually:
this.props.avgRating
By the way, you should not have a props that starts with an upper case letter
Upvotes: 3