In ReactJS, "props" (short for properties) are a way to pass data from a parent component to a child component. Props are read-only and should not be modified within the child component.
Here's how to use props in ReactJS:
Define the props in the parent component:
import React from 'react';
function ParentComponent(props) {
return (
<ChildComponent message={props.message} />
);
}
export default ParentComponent;
Access the props in the child component:
import React from 'react';
function ChildComponent(props) {
return (
<div>
{props.message}
</div>
);
}
export default ChildComponent;
In the example above, the parent component passes a prop called a message to the ChildComponent, which can access the value of the message via props. message.
Props can be of any type, including strings, numbers, objects, and even functions.
It's also possible to specify default values for props, in case the parent component doesn't pass a specific prop:
function ChildComponent(props) {
return (
<div>
{props.message || 'This is a default message.'}
</div>
);
}
In the example above, if the ParentComponent doesn't pass a message prop, the ChildComponent will display the default message "This is a default message."
Check Out: ReactJS course in Bangalore
Comments