React Props
Props are read-only data passed to React Components as arguments. They are like attributes in HTML, and arguments in Javascript.
To pass a prop to a component, use the same syntax as we have for HTML attributes:
<ReactComp name="Robert" />
All the props are received by the component as props
object:
class ReactComp extends React.Component {
render() {
return <p>I am {this.props.name}!</p>
}
}
The output will be:
I am Robert
Passing data using Props
Props are used to send data from one component to another. To pass a variable as a prop, enclose it within {}
curly brackets.
Here's an example:
User.js
import React from 'react'
class User extends React.Component {
render() {
return <h1>I am {this.props.name} and age is {this.props.age}</h1>
}
}
Passing props from the other component:
App.js
import React from 'react'
import User from './User'
class App extends React.Component {
render() {
const user_age = 28;
return (
<div>
&h1>Main Component </h1>
<User age={user_age} name="Robert"/>
</div>
)
}
}
Passing Props to Constructor
If the component is receiving props and has a constructor function, the props need to be passed to the constructor and to the base class via super()
method. Here's an example:
class User extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<p> Hello {this.props.name} </p>
</div>
)
}
}
ReactDOM.render(<User name="Robert"/>, document.getElementById('root'));