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 use ReactJS to require modules?
- How do I quickly get started with ReactJS?
- How can I use a ReactJS obfuscator to protect my code?
- How do I zip multiple files using ReactJS?
- How can I become a React.js expert from scratch?
- How do I download ReactJS from reactjs.org?
- How can I use React.js to parse XML data?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How do I install Yarn for React.js?
- How can I use OAuth2 with ReactJS?
See more codes...