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 can I use zxcvbn in a ReactJS project?
- How do I zip multiple files using ReactJS?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How can I become a React.js expert from scratch?
- How can I use an online compiler to write ReactJS code?
- How do I set the z-index of a ReactJS component?
- How do I create a zip file using ReactJS?
- How can I use ReactJS to zoom in and out of elements on a page?
- How can I use ReactJS Zustand to manage state in my application?
- How can I use Yup with ReactJS?
See more codes...