0

It is the second time that I try to define a defaultProps on React, but isn't showing nothing, like is undefined

The UserGreeting component:

import PropTypes from 'prop-types'

function UserGreeting(props) {

    if (props.isLoggedIn)  {
        return (
            <h2>
                Welcome {props.username}!
            </h2>
        )
    } else {
        return (
            <h2>
                Please Log in!
            </h2>
        )
    }

}

UserGreeting.proptypes = {
    isLoggedIn: PropTypes.bool,
    username: PropTypes.string,
}

UserGreeting.defaultProps = {
    isLoggedIn: false,
    username: "Guest",
}

export default UserGreeting

And the App component:

import UserGreeting from "./UserGreeting"

function App() {
  

  return (
    <>
      <UserGreeting isLoggedIn={true} username="Bob" />
    </>
  )
}

export default App

When i run it, just show as the props is undefined when nothing is passed

It worked when I did this: Welcome {props.username ?? "Guest"}!

But i really want to understand why the defaultProps isn't working

3
  • This question is similar to: React functional component default props vs default parameters. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Feb 21 at 2:27
  • @joaorhauan what version of react are you using? default props for function components was removed in react 19 and deprecated in 18.3 Commented Feb 21 at 3:19
  • @NicholasTower Oh, didn't know that. Thank you. Commented Feb 23 at 1:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.