Understanding React Props with Examples
Introduction:
In this article, we will dive into the fascinating world of React props, exploring what they are, how they work, and why they are essential in the development of modern web applications. Whether you’re a seasoned React developer looking to deepen your understanding or a newcomer eager to grasp the basics, this guide will provide you with valuable insights into this fundamental concept, empowering you to build more flexible and interactive user interfaces. Let’s begin our journey into the realm of React props and unlock the potential they offer in crafting dynamic web experiences.
Props
Props, short for “properties,” are a core concept in React that allows you to pass data from a parent component to its child components. They provide a way to make components dynamic and customizable by allowing external values to influence their behavior and rendering. React Props are read-only and cannot be modified within the receiving component.
There are two main types of props in React:
Regular Props: These are the most common types of props that you pass to components. They are passed as attributes to the child component’s JSX element. The child component can access and use these props within its rendering logic.
Children Props: Sometimes referred to as “children,” these are the contents between the opening and closing tags of a component in JSX. They can be accessed using the props.children property within the component.
Regular React Props
Example 1: Displaying a Greeting using Regular Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import React from 'react'; const Greeting = (props) => { return <h1>Hello, {props.name}!</h1>; }; const App = () => { return <Greeting name="Alice" />; }; export default App; |
In this example, the Greeting component takes a name prop and displays a personalized greeting.
Example 2: Dynamic User Information using Regular Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import React from 'react'; const UserInfo = (props) => { return ( <div> <p>Name: {props.name}</p> <p>Age: {props.age}</p> </div> ); }; const App = () => { return <UserInfo name="Fawad khan" age={28} />; }; export default App; |
Here, the UserInfo component uses react props to display dynamic user information.
Example 3: Rendering a List using Regular Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import React from 'react'; const List = (props) => { const items = props.items.map((item, index) => ( <li key={index}>{item}</li> )); return <ul>{items}</ul>; }; const App = () => { const fruitList = ['Apple', 'Banana', 'Orange']; return <List items={fruitList} />; }; export default App; |
This example showcases using react props to render a list of items.
Example 4: Styling Component using Regular Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import React from 'react'; const StyledText = (props) => { const style = { color: props.color, fontSize: props.fontSize, }; return <p style={style}>{props.text}</p>; }; const App = () => { return ( <StyledText text="Hello, Styling!" color="blue" fontSize="20px" /> ); }; export default App; |
In this example, the StyledText component receives styling-related react props.
Example 5: Handling Events using Regular Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import React from 'react'; const Button = (props) => { return ( <button onClick={props.onClick}>{props.label}</button> ); }; const App = () => { const handleClick = () => { alert('Button Clicked!'); }; return <Button label="Click Me" onClick={handleClick} />; }; export default App; |
Here, the Button component uses props to manage event handling.
Children React Props
Example 1: Displaying Text Inside a Wrapper using Children React Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import React from 'react'; const Wrapper = (props) => { return <div className="wrapper">{props.children}</div>; }; const App = () => { return ( <Wrapper> <p>This text is wrapped.</p> </Wrapper> ); }; export default App; |
In this example, the Wrapper component uses props.children to wrap the content passed between its opening and closing tags.
Example 2: Creating a Modal Component using Children React Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import React from 'react'; const Modal = (props) => { return ( <div className="modal"> <div className="modal-content">{props.children}</div> </div> ); }; const App = () => { return ( <Modal> <h2>Welcome to the Modal</h2> <p>This is the content of the modal.</p> </Modal> ); }; export default App; |
Here, the Modal component uses props.children to render the content of a modal.
Example 3: Custom Button Component using Children Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import React from 'react'; const CustomButton = (props) => { return ( <button className="custom-button"> {props.icon} {props.children} </button> ); }; const App = () => { return ( <CustomButton icon="🚀">Launch</CustomButton> ); }; export default App; |
This example demonstrates using props.children to create a custom button component with an icon.
Example 4: Wrapping Multiple Elements using Children Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import React from 'react'; const Card = (props) => { return ( <div className="card"> {props.children} </div> ); }; const App = () => { return ( <Card> <h3>Title</h3> <p>Content goes here.</p> <button>Click</button> </Card> ); }; export default App; |
In this example, the Card component wraps multiple elements using props.children.
Example 5: Dynamic Content in a Wrapper using Children Props
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import React from 'react'; const Wrapper = (props) => { const bgColor = props.backgroundColor || 'white'; const style = { backgroundColor: bgColor, padding: '20px', borderRadius: '5px', }; return ( <div style={style}> {props.children} </div> ); }; const App = () => { return ( <Wrapper backgroundColor="lightblue"> <p>This content has a light blue background.</p> </Wrapper> ); }; export default App; |
Here, the Wrapper component accepts both background color and children props to create a customizable wrapper.
Passing Functions as Props
Passing Functions as Props is a powerful concept in React that allows you to send functions from parent components to child components. This enables child components to invoke these functions, facilitating communication and interaction between components. Passing functions as props is a key way to implement callback mechanisms and allow child components to trigger actions in their parent components.
Passing Functions as Props Examples:
Example 1: Button Click Handler using Passing Functions as Props
Parent component passes a function to a child component as a prop. The child component uses this function as an event handler.
ParentComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
//ParentComponent.js file import React from 'react'; import ChildButton from './ChildButton'; class ParentComponent extends React.Component { handleClick = () => { alert('Button clicked in parent component!'); }; render() { return <ChildButton onClick={this.handleClick} />; } } export default ParentComponent; |
ChildButton js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//ChildButton.js file import React from 'react'; const ChildButton = (props) => { return <button onClick={props.onClick}>Click Me</button>; }; export default ChildButton; |
App js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//App.js file import React from 'react'; import ParentComponent from './ParentComponent'; const App = () => { return ( <div> <h1>App Component</h1> <ParentComponent /> </div> ); }; export default App; |
Example 2: Updating State in Parent Component using Passing Functions as Props
The parent component passes a function to update its state to a child component. The child component triggers state updates in the parent.
ParentComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
//ParentComponent.js file import React from 'react'; import ChildComponent from './ChildComponent'; class ParentComponent extends React.Component { state = { count: 0, }; updateCount = () => { this.setState((prevState) => ({ count: prevState.count + 1 })); }; render() { return <ChildComponent count={this.state.count} updateCount={this.updateCount} />; } } export default ParentComponent; |
ChildComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//ChildComponent.js file import React from 'react'; const ChildComponent = (props) => { return ( <div> <p>Count: {props.count}</p> <button onClick={props.updateCount}>Increment</button> </div> ); }; export default ChildComponent; |
App js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//App.js file import React from 'react'; import ParentComponent from './ParentComponent'; const App = () => { return ( <div> <h1>App Component</h1> <ParentComponent /> </div> ); }; export default App; |
Example 3: Dynamic Content in Child Component using Passing Functions as Props
Passing a function to a child component allows it to generate dynamic content based on props.
ParentComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//ParentComponent.js file import React from 'react'; import ChildComponent from './ChildComponent'; class ParentComponent extends React.Component { render() { return <ChildComponent generateContent={(num) => `Value: ${num}`} />; } } export default ParentComponent; |
ChildComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//ChildComponent.js file import React from 'react'; const ChildComponent = (props) => { const content = props.generateContent(100); return <p>{content}</p>; }; export default ChildComponent; |
App js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//App.js file import React from 'react'; import ParentComponent from './ParentComponent'; const App = () => { return ( <div> <h1>App Component</h1> <ParentComponent /> </div> ); }; export default App; |
Example 4: Customizing Child Behavior using Passing Functions as Props
Passing functions as props lets you customize the behavior in child components.
ParentComponent js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
//ParentComponent.js file import React from 'react'; import ChildComponent from './ChildComponent'; class ParentComponent extends React.Component { handleChildClick = () => { alert('Parent says child was clicked!'); }; render() { return ( <ChildComponent onClick={this.handleChildClick} customText="Click Me" /> ); } } export default ParentComponent; |
ChildComponent js file Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//ChildComponent.js file import React from 'react'; const ChildComponent = (props) => { return ( <button onClick={props.onClick}>{props.customText}</button> ); }; export default ChildComponent; |
App js file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//App.js file import React from 'react'; import ParentComponent from './ParentComponent'; const App = () => { return ( <div> <h1>App Component</h1> <ParentComponent /> </div> ); }; export default App; |
Default Props
Default Props is a feature in React that allows you to set default values for props in a component. These default values are used when a parent component does not explicitly pass a value for a particular prop to its child component. Default props ensure that your component behaves as expected even when certain props are missing.
Default props Examples:
Example 1: Setting Default Value for a Prop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import React from 'react'; const Greeting = (props) => { return <h1>Hello, {props.name}!</h1>; }; Greeting.defaultProps = { name: 'Guest', // Default value for the 'name' prop }; const App = () => { return <Greeting />; }; export default App; |
In this example, the Greeting component has a default prop value for name, which is used when the parent component (App) doesn’t pass a value for name.
Example 2: Default Props with Functional Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React from 'react'; const Message = (props) => { return <p>{props.text}</p>; }; Message.defaultProps = { text: ' Default message', // Default value for the 'text' prop }; const App = () => { return <Message />; }; export default App; |
Here, the Message functional component has a default value for the text prop, ensuring that it displays the default message when the prop is not provided by the parent component.
Example 3: Default Props with Class Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import React from 'react'; class Counter extends React.Component { constructor(props) { super(props); this.state = { count: props.initialCount }; } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } } Counter.defaultProps = { initialCount: 0, // Default value for the 'initialCount' prop }; const App = () => { return <Counter />; }; export default App; |
In this example, the Counter class component has a default value for the initialCount prop. If the parent component doesn’t provide this prop, the component starts with the default initial count.
Default props are useful for providing sensible fallback values when certain props are missing. They contribute to making your components more resilient and predictable in various scenarios.
Conclusion
In this article, we’ve explored the core concepts of React props. Components serve as the foundation of your UI, allowing you to create modular and reusable pieces. Props enable you to pass data between components, making them versatile and adaptable to various use cases. By mastering these concepts, you’ll be well-equipped to build dynamic and interactive user interfaces using React.
Remember, the key to becoming proficient with React lies in practice. Experiment with different components and props to deepen your understanding and create impactful applications.