Reputation: 141
Ok so I load the root url. A post list should be rendered, instead I get the infamous React error...
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
index.js and app.js appear to render properly. I believe the malfunction is in the PostList component, perhaps the render method? I know the solution is probably pretty simple, but I cannot see it.
index.js
7
8 ReactDOM.render(
9 <React.StrictMode>
10 <HashRouter>
11 <App />
12 </HashRouter>
13 </React.StrictMode>,
14 document.getElementById('root')
15 );
16
17
18
19
20 reportWebVitals();
app.js
8
9 class App extends React.Component {
10
11 constructor() {
12 super();
13 this.state = {
14 posts: []
15 };
16 }
17
18 componentDidMount() {}
19
20 render() {
21 return (
22 <div className="container">
23 <h1>hello world</h1>
24 <Routes>
25 <Route exact path='/' element={PostList} />
26 <Route path='/post/:id' element={Post} />
27 </Routes>
28 </div>
29 );
30 }
31 }
32
33 export default App;
post-list.js
5
6 class Post extends React.Component {
7 constructor() {
8 super();
9 this.state = {
10 title: '',
11 content: ''
12 };
13 }
14
15 componentDidMount() {
16 let api = new Api();
17
18 api.posts(this.props.match.params.id).then(data => {
19 this.setState({
20 title: data.title.rendered,
21 content: data.content.rendered
22 });
23 });
24 }
25
26 render() {
27 let post = this.state;
28 return (
29 <div className='row'>
30 <h3>{post.title}</h3>
31 <div dangerouslySetInnerHTML={{__html: post.content}} />
32 </div>
33 );
34 }
35 }
36
37 class PostList extends React.Component {
38 constructor() {
39 super();
40 this.state = {
41 posts: []
42 };
43 }
44
45 componentDidMount() {
46 let api = new Api();
47
48 api.posts().then(data => {
49 this.setState({
50 posts: data
51 });
52 });
53 }
54
55 render() {
56 let posts = this.state.posts.map((post, index) =>
57 <h3 key={index}>
58 <Link to={`/post/${post.id}`}>{post.title.rendered}</Link>
59 </h3>
60 );
61
62 return (
63 <div>{posts}</div>
64 );
65 }
66 }
67
68 export {Post, PostList}
Upvotes: 1
Views: 124
Reputation: 88
Apparently you have a problem in configuring the routes
You can check the part of configuring routes in the documentation of React Router https://reactrouter.com/docs/en/v6/getting-started/overview
Try to replace the PostList and Post in line 25 and 26 in your app.js file as following
<Route exact path='/' element={<PostList/>} />
<Route path='/post/:id' element={<Post/>} />
Upvotes: 1