Props are properties to be used inside a component. They act as global object or variables which can be used inside the Component.
Props to Function Component
Here is an example of passing props to a function component.
import React from 'react';
import ReactDOM from 'react-dom';
function Hello(props) {
return <h1>{props.msg}</h1>;
}
const Hello_comp = <Hello msg="Hello, from Viastudy Tutorials!" />;
export default Hello_comp;
As shown above, we have added msg attribute to <Hello /> Component. The same can be accessed as props inside Hello function, which is an object that will have the msg attribute details, and the same is used as an expression.
The component is used in index.js as follows:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello_comp from './test.jsx';
ReactDOM.render(
Hello_comp,
document.getElementById('root')
);
Here is the output in the browser:
Props to Function Component
Here is an example of passing props to a function component.
import React from 'react';
import ReactDOM from 'react-dom';
function Hello(props) {
return <h1>{props.msg}</h1>;
}
const Hello_comp = <Hello msg="Hello, from Viastudy Tutorials!" />;
export default Hello_comp;
As shown above, we have added msg attribute to <Hello /> Component. The same can be accessed as props inside Hello function, which is an object that will have the msg attribute details, and the same is used as an expression.
The component is used in index.js as follows:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello_comp from './test.jsx';
ReactDOM.render(
Hello_comp,
document.getElementById('root')
);
Here is the output in the browser:
Props to Class Component
To access the props in a class we can do it as follows:
test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component {
render() {
return <h1>{this.props.msg}</h1>;
}
}
export default Hello;
The msg attribute is passed to the component in index.js as follows:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './test.jsx';
ReactDOM.render(
<Hello msg="Hello, from Viastudy Tutorials!" />,
document.getElementById('root')
);
This is the output in the browser:
No comments:
Post a Comment