reactjsHow do I use ReactJS props?
Props are a way of passing data from a parent component to a child component in React. Props are read-only and should not be modified within the child component.
Example
// Parent Component
import React from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
render() {
return (
<ChildComponent message="Hello World!" />
)
}
}
export default ParentComponent;
// Child Component
import React from 'react';
class ChildComponent extends React.Component {
render() {
return (
<div>
{this.props.message}
</div>
)
}
}
export default ChildComponent;
Output example
Hello World!
The code above is composed of two components, the ParentComponent and the ChildComponent. In the ParentComponent, a prop called message
is passed to the ChildComponent. In the ChildComponent, the message
prop is accessed via this.props.message
and rendered to the screen.
Code explanation
import React from 'react'
: This line imports the React library, which is necessary for writing React components.class ParentComponent extends React.Component
: This line creates a new React component called ParentComponent, which is a subclass of React.Component.<ChildComponent message="Hello World!" />
: This line renders the ChildComponent, passing in a prop calledmessage
with a value ofHello World!
.class ChildComponent extends React.Component
: This line creates a new React component called ChildComponent, which is a subclass of React.Component.this.props.message
: This line accesses themessage
prop that was passed into the ChildComponent.<div>{this.props.message}</div>
: This line renders the value of themessage
prop inside of a div.
Helpful links
More of Reactjs
- How do I create a zip file using ReactJS?
- How do I set the z-index of an element in React.js?
- How do I use ReactJS to create an example XLSX file?
- How do I convert XML to JSON using ReactJS?
- How can I use a ReactJS XML editor?
- How do I use React JS with W3Schools?
- How do I set the z-index of a ReactJS component?
- How do I implement a year picker using ReactJS?
- How can I use ReactJS to create a window?
- How can I use ReactJS to implement a websocket connection?
See more codes...