Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React proptypes component vs element

What is the difference between :

var Icon = React.createClass({
  propTypes: {
    name: React.PropTypes.string
  },
  render: function(){
    return (
      <span className={'glyphicon glyphicon-'+this.props.name}></span>
    );
  }
});

var Button = React.createClass({
  propTypes: {
    content: React.PropTypes.element // This one?
    content: React.PropTypes.component // Or this one?
  },
  render: function() {
    return (
       <button>{content}</button>
    );
  }
});

I'd like to use;

<Button content={<Icon name="heart" />} />

In which case should I use the other?

Thanks

like image 888
Augustin Riedinger Avatar asked Mar 21 '15 18:03

Augustin Riedinger


People also ask

What is the PropTypes for a React component?

What Are PropTypes In React? # PropTypes are a mechanism to ensure that components use the correct data type and pass the right data, and that components use the right type of props, and that receiving components receive the right type of props.

Should I use PropTypes in React?

Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.

Can we use PropTypes in functional component?

In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by React.memo or React.forwardRef . PropTypes exports a range of validators that can be used to make sure the data you receive is valid.

Should I use PropTypes or typescript?

Typescript and PropTypes serve different purposes. Typescript validates types at compile time, whereas PropTypes are checked at runtime. Typescript is useful when you are writing code: it will warn you if you pass an argument of the wrong type to your React components, give you autocomplete for function calls, etc.


1 Answers

I think you should render the Button like this:

var Button = React.createClass({
  render: function() {
    return (
       <button>{this.props.children}</button>
    );
  }
});

Then you can use it with an <Icon /> or anything else (text...) :

<Button><Icon name="heart" /></Button>

or

<Button>anything</Button>

And then the correct proptype depends on what you want to allow inside your <Button /> (But I'm not sure React.PropTypes.component exists, it's not in the documentation: http://facebook.github.io/react/docs/reusable-components.html)

like image 55
al8anp Avatar answered Oct 30 '22 03:10

al8anp