Posted

2 minutes read

Props definition and role

Usually we want the components to display dynamical data, not just static data. For that we need to pass that information to the components.

Props represent the mechanism used by components to talk to each other.
Props represent the short term from properties.

The way to pass this down to the components is by adding HTML attributes to the JSX code of the user defined element.

When React gets to a user defined element that has attributes it will pass this to the component as a single object which is called props.

Example passing props in a function component:


import React from 'react';
import LoginBar from './LoginBar';

function App(props){
	const username = 'John';
	return <LoginBar username={username}></LoginBar>
}

export default App;

Example passing props in a class component:


import React, { Component} from 'react';
import LoginBar from './LoginBar';

class App extends Component{
	
	render(){
		const username = 'John';
		return <LoginBar username={username}></LoginBar>
	}
}

export default App;

In the examples above we pass a props object that will have a field props.username with a value equal to John.

Default props

The props can have a default value used in the case of the parent component not passing down the props for a component.

Example using default value props in a function component:


import React from 'react';

function LoginBar(props) {
	return <h1> Logged in as {props.username} </h1>
}

LoginBar.defaultProps = {
	username: 'Tom',
}

export default LoginBar;

Example using default value props in a class component:


import React, { Component } from 'react';

class LoginBarClassComponent extends Component{

	render(){
		return(
			<h1> Logged in as {this.props.username} </h1>
		);
	}
}

LoginBarClassComponent.defaultProps = {
	username: 'Tom',
}

export default LoginBarClassComponent;

Props are immutable

This means that props can be considered read only. Their value cannot be changed.

Summary

Props are used to pass data from parent to child.
They are immutable and we can assign a default value to props.





Thanks for reading. I hope you learned something interesting about React!
If you found this article useful, please share it with others. Don’t forget to subscribe to get notified for the upcoming articles.