I cannot use defaultProps in React

Asked

Viewed 23 times

1

I’m a beginner in React, and I’m trying to set a default value for a prop if it’s not passed, but it’s not working.

Title.js

import React, { Component } from 'react';

export default class Title extends Component {
    render() {
        return (
            <div>
                <h1>Hello, {this.props.name  }</h1>
            </div>
        );
    }
}

Title.defaultProps = {
    name:'Janio Carvalho Jr'
}

App.js

function App() {
  return (

    <div className='container'>
        <Title name  />
    </div>
  );
};

1 answer

1


You are using wrong, remove the name of the property that will work, example:

class Title extends React.Component {
    render() {    
        return (
            <div>
                <h1>Hello, {this.props.name  }</h1>
            </div>
        );
    }
}

Title.defaultProps = {
    name:'Janio Carvalho Jr'
}

function App() {
  return (
    <div className='container'>
        <Title/>
    </div>
  );
};


ReactDOM.render(<App/> , document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>

You do not need to place the property in the component if you also do not need to pass value, it is only necessary when passing a specific value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.