Hi, I am using React and having trouble rendering a simple element (<p>hello<p>
) in my class-based component called SingleRoom. I have copied the code from my App.js, Room.js, and SingleRoom.js files. Let me walk you through the structure. Using a switch statement, the App.js file routes the user to the SingleRoom.js file if the exact path is /rooms/:slug. The Room.js file has a link to the SingleRoom.js file which is represented as a string literal /rooms/${slug}
. When the user clicks on the link, I expected the SingleRoom component to render the following text “hello.” However, the SingleRoom aforementioned text is not rendered. I do not receive any errors. If i console.log in the component, I do receive the output which implies that the component is partially rendering. I believe this may have to do with the fact that the state of SingleRoom is not being changed so React will not render the entire component. I’ve tried to research a workaround but the solutions don’t seem to apply to my situation. On a side note, if I add a SEPARATE component before the <p>hello<p>
element in the SingleRoom component, both the separate component and the <p>
element become rendered. Please let me know if you have any suggestions. Thanks in advance.
App.js file:
import React from "react";
import Home from "./pages/Home";
import Rooms from "./pages/Rooms";
import SingleRoom from "./pages/SingleRoom";
import Error from "./pages/Error";
import { Route, Switch } from "react-router-dom";
import Navbar from "./components/Navbar";
import "./App.css";
function App() {
return (
<>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/rooms/" component={Rooms} />
<Route exact path="/rooms/:slug" component={SingleRoom} />
<Route component={Error} />
</Switch>
</>
);
}
export default App;
Room.js file:
import React from "react";
import { Link } from "react-router-dom";
import defaultImg from "../images/room-1.jpeg";
import propTypes from "prop-types";
export default function Room({ room: roomProp }) {
const { name, slug, images, price } = roomProp;
return (
<article className="room">
<div className="img-container">
<img src={images[0] || defaultImg} alt="single room" />
<>
<div className="price-top">
<h6>${price}</h6>
<p>per night</p>
</div>
<Link to={`/rooms/${slug}`} className="btn-primary room-link">
Features
</Link>
</>
</div>
<p className="room-info">{name}</p>
</article>
);
}
Room.propTypes = {
room: propTypes.shape({
name: propTypes.string.isRequired,
slug: propTypes.string.isRequired,
images: propTypes.arrayOf(propTypes.string).isRequired,
price: propTypes.number.isRequired
})
};
SingleRoom.js file:
import React, { Component } from "react";
export default class SingleRoom extends Component {
render() {
return (
<p>hello</p>
);
}
}