In my UserGreeting.jsx file, I have added the default values for my username variable, however, when I'm trying to render it by removing the username value in the app.jsx file, it's not showing up in the website:
UserGreeting.jsx =
import PropTypes from 'prop-types'
function UserGreeting(props) {
return (
props.isLoggedIn ?
<h2 className="welcome-msg">Welcome {props.username}</h2>
: <h2 className="login-prompt">Please login to continue</h2>
)
}
UserGreeting.propTypes = {
isLoggedIn: PropTypes.bool,
username: PropTypes.string
}
UserGreeting.defaultProps = {
isLoggedIn: false,
username: "Unknown",
}
export default UserGreeting
App.jsx
import UserGreeting from "./UserGreeting"
function App() {
return (
<>
<UserGreeting isLoggedIn={true} />
</>
)
}
export default App
I'm following the BroCode React tutorial and this was shown in the "props" and "conditional rendering" chapters. I have checked all the possible typos and if my code looks any different from the tutorial
It looks like the mentioned tutorial is old and outdated because the Component.defaultProps()
has been deprecated. The recommendation is to use either Typescript for type safety rather than using the "prop-types" library or use the JavaScript's default parameter. Since you're using plain JavaScript, I have adjusted your UserGreeting
component to use default parameters instead of the defaultProps.
function UserGreeting({isLoggedIn = false, username = "Unknown"}) {
return (
isLoggedIn ?
<h2 className="welcome-msg">Welcome {username}</h2>
: <h2 className="login-prompt">Please login to continue</h2>
)
}
export default UserGreeting