Components And Props
Bipin Rajbhar
Posted on October 30, 2020
What is a component?
In simple words, a component is just a function that returns something that is renderable (React Element, String, Number, etc.).
Component name must start with capital letters.
// functional component
function Greeting() {
return null;
}
What is Props?
Props are optional arguments that you can use to pass the data to the component.
// functional component with props
function Greeting(props) {
return <em>{props.greeting}, {props.subject}</em>;
}
Let's create a reusable Greeting component.
Sample Code
function Greeting(props) {
// jsx
return <em>{props.greeting}, {props.subject}</em>;
}
Example 1
What is PropTypes?
PropTypes allows you to validate the property of the component at runtime.
PropTypes validation feature is only available in the development.
Let's validate the greeting
and subject
property of the Greeting component.
Sample Code
<script type="text/babel">
function Greeting(props) {
return <em>{props.greeting}, {props.subject}</em>
}
// propType validation
const PropTypes = {
string(props, propName, componentName) {
console.log()
if(typeof props[propName] !== 'string') {
console.log()
throw new Error(`${propName} must be string for the ${componentName} component but you have passed ${typeof props[propName]}.`);
}
}
}
Greeting.propTypes = {
greeting: PropTypes.string,
subject: PropTypes.string
}
ReactDOM.render(<Greeting greeting="Hello" subject="Bipin Rajbhar"/>, document.getElementById('root'));
</script>
If the type of
greeting
andsubject
is other than the string, it will throw an error.
Example 2
Using the prop-types package
As it turns out, you want to validate some pretty common things, so the React team maintains a package called props-types.
To use the prop-types package, we need to add a JavaScript file.
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
Now, you have a global Object available called
PropTypes
.
Sample Code
<script type="text/babel">
function Greeting(props) {
return <em>{props.greeting}, {props.subject}</em>
}
Greeting.propTypes = {
greeting: PropTypes.string,
subject: PropTypes.string
}
ReactDOM.render(<Greeting greeting="Hello" subject="Bipin Rajbhar"/>, document.getElementById('root'));
</script>
Example 3
I hope you learned something from this article and if you have any doubts, please leave a comment. I will be delighted to answer all of your questions.
My name is Bipin Rajbhar and I am a software engineer at QuikieApps; and you can follow or connect to me on Twitter and Linked In
Read more
Resources
The Beginner's Guide to React
Epic React
Posted on October 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.