Table of contents
Props
In React class components, you can pass props from a parent component to a child component by setting them as properties of the child component instance in the parent component's render method. Here's an example:
// Parent component class ParentComponent extends React.Component { render() { const message = "Hello, world!"; return ( <ChildComponent message={message} /> ); } } // Child component class ChildComponent extends React.Component { render() { return ( <div>{this.props.message}</div> ); } }
In this example, the parent component
ParentComponent
sets themessage
prop with the value"Hello, world!"
and passes it to the child componentChildComponent
by rendering it with themessage
prop as a property of the child component instance.The child component accesses the
message
prop through itsprops
object in therender
method and displays it in adiv
element.In React, props are passed down to components as JavaScript objects. When you pass a prop to a component, React creates a new object to represent the props and sets the prop values as properties of that object.
example:
<ChildComponent name="John" age={25} />
Here, we're passing two props to the ChildComponent component: name and age.
React creates a new object to represent these props, which might look something like this:
{ name: "John", age: 25 }
This object is then passed as a single argument to the
ChildComponent
function when it's rendered. Within the component, we can access the prop values using theprops
object.React also has built-in mechanisms for handling default props and type-checking for props using PropTypes.
These can help ensure that your components receive the correct props and handle them appropriately.