You must note that React is a Single Page application
. And to introduce Routes in your Application you will need a third party library, react-router-dom
is one of those libraries.
So, doing window.location="/result"
doesn't mean anything here. In Single Page application, we don't have a seperate HTML page called results.html
. It's just one huge SPA (index.html)
and everything goes with our root
div in our index.html
in the public folder.
<div id="root"></div>
I will not go with each and every detail about react-router-dom
. Go through this documentation to get started.
https://reactrouter.com/web/guides/quick-start
UPDATE: From comment, It seems you also wants to know about passing the score
to Child Component.
To link b/w different components in your app, you should go with react-router-dom
as mentioned above.
CASE B: In order to pass the score
to the Result
component, you do not need to use <Result points={this.state.score} />
nor window.location
in your handleSubmit()
method. The way you have done this will result in error in your app.
You simply need to use your Result
component within Game
component inside the render()
function within return()
.
Game.js Should look like below code. So that Result
Component gets rendered within Game
Component.
import React, { Component } from "react";
import Result from "./Result";
class Game extends Component {
constructor(props) {
super(props);
this.state = {
score: 34
};
}
render() {
return (
<div>
<Result points={this.state.score} />
</div>
);
}
}
export default Game;
a) Also I checked that you have imported Game
Component in Result
Component. That is not needed at all. This will ultimately mean You will render a parent component Game
in the child component Result
.
FULL CODE DEMO OF HOW BOTH YOU YOUR COMPONENTS SHOULD LOOK LIKE :
const {Component} = React;
class Game extends Component {
constructor(props) {
super(props);
this.state = {
score: 34
};
}
render() {
return (
<div>
<Result points={this.state.score} />
</div>
);
}
}
class Result extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<section className="result">
<div className="lContainer">
<div class="rheading">Congratulation's your Score was:</div>
<div className="points">{this.props.points} </div>
</div>
</section>
</div>
);
}
}
ReactDOM.render(<Game/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…