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 calledmessagewith 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 themessageprop that was passed into the ChildComponent.<div>{this.props.message}</div>: This line renders the value of themessageprop inside of a div.
Helpful links
More of Reactjs
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How do I zip multiple files using ReactJS?
- How do I create a zip file using ReactJS?
- How do I use Yup validation with ReactJS?
- How do I install Yarn for React.js?
- How can I use Yup with ReactJS?
- How can I use a ReactJS XML editor?
- How can I use ReactJS and Kafka together to develop a software application?
- How do I implement a year picker using ReactJS?
- How can I use zxcvbn in a ReactJS project?
See more codes...