React Props
- Props, short for "properties," are read-only components that store attribute values similarly to HTML attributes. They allow data to be passed from one component to another, much like function arguments are passed to a function.
- Props are immutable, meaning they cannot be modified from within the component. However, components can receive attributes called props, which are accessible within the component as `this.props`. These props can be used to render dynamic data in the component's `render` method.
- When you need immutable data within a component, you should pass props to the `ReactDOM.render()` method in the `main.js` file of your ReactJS project. These props can then be used inside the component as needed. This process is illustrated in the example below.
Example
App.js
class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to { this.props.name } </h1>
<p>
<h4>Gocourse is the best learning website for students,beginners,etc...</h4>
</p>
</div>
);
}
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App name = "Gocourse!!" />, document.getElementById('app'));
Output
Default Props
It isn't always necessary to pass props through the `ReactDOM.render()` method. You can also define default props directly within the component's constructor. This is illustrated in the example below.
Example
App.js
import React, { Component } from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>Default Props Example</h1>
<h3>Welcome to {this.props.name}</h3>
<p>Gocourse is the best learning website for students,beginners,etc...</p>
</div>
);
}
}
App.defaultProps = {
name: "Gocourse"
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));
Output
You can combine both state and props in your app by setting the state in a parent component and passing it to a child component via props. This is demonstrated in the example below.
Example
App.js
import React, { Component } from 'react';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
userName: "JohnDoe",
userAge: 28
};
}
render() {
return (
<div>
<UserProfile
name={this.state.userName}
age={this.state.userAge}
/>
</div>
);
}
}
class UserProfile extends Component {
render() {
return (
<div>
<h1>User Profile</h1>
<h3>Name: {this.props.name}</h3>
<p>Age: {this.props.age}</p>
<p>Welcome to our Gocourse platform! We are glad to have you here.</p>
</div>
);
}
}
export default Dashboard;