Reputation: 1956
I am very new to react learning, I have started working with Router in react.js
.
When I am trying to make Router I am getting this error A <Router> may have only one child element Error in react
.
My code is as follows:
File : Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
File : App.js
import React, { Component } from 'react';
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import Home from "./Home";
import Stuff from "./Stuff";
import Contact from "./Contact";
class App extends Component {
render() {
return (
<HashRouter>
<div>
<div>
<h1>Simple SPA</h1>
<ul className="header">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/stuff">Stuff</NavLink></li>
<li><NavLink to="/contact">Contact</NavLink></li>
</ul>
</div>
<div className="content">
<Route exact path="/" component={Home}/>
<Route path="/stuff" component={Stuff}/>
<Route path="/contact" component={Contact}/>
</div>
</div>
</HashRouter>
);
}
} export default App;
There are separate files for Home.js, Stuff.js and Contact.js.
I have even tried to use Switch
, but still getting the same error.
Can anybody suggest what's going wrong here?
Upvotes: 2
Views: 945
Reputation: 1704
I've just encountered this exact same error and it's because I copy-pasted some code which had non breaking space characters (U+00A0) instead of spaces, so extra text nodes were being generated! After replacing with actual spaces, everything worked!
Upvotes: 2
Reputation: 1534
Your App.js looks fine. That really strange. Are you sure you have built this code?
You may try to change your index.js to:
import React from 'react';
import {
HashRouter
} from "react-router-dom";
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<HashRouter><App /></HashRouter>, document.getElementById('root'));
And remove HashRouter
from App.js. Check if it helps.
Upvotes: 3