juan garcia
juan garcia

Reputation: 1516

Is it possible to create a React component interface?

I have the following react component:

class Cmp extends React.Component {
  render () {
    return <h3>{this.props.title}</h3>;
  }
}

But I would like to expose or say to the consumer of my component to use it with a title otherwise it does not work the component.

Consumer would use it like

<Cmp title='Some fancy title' />

I need the consumer of my component to know that he should provide a title otherwise the component does not have any sense.

Upvotes: 0

Views: 3074

Answers (2)

user1902408
user1902408

Reputation:

If you return null from a render method, nothing is rendered. You could use this knowledge to conditionally check if the prop is passed, and return null if the prop is not passed. The advantage here over using componentWillReceiveProps() is that you could use a functional component rather than a class component.

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

Preventing Component from Rendering

Realistically you would also use PropTypes.

Cmp.propTypes = {
  title: PropTypes.string.isRequired
};

Short Example

import React from 'react';
import PropTypes from 'prop-types';

const Cmp = (props) => props.title ? <h3>{props.title}</h3> : null

Cmp.propTypes = {
  title: PropTypes.string.isRequired
}

export default Cmp;

Upvotes: 1

Janick Fischer
Janick Fischer

Reputation: 636

You can use PropTypes and set it to isRequired. You can also check if the prop is set at componentWillReceiveProps() and throw your error.

Upvotes: 7

Related Questions