Understanding and Using Props in React Components: Passing Data and Building Reusable UI Elements

Learn how to use props in React to pass data from parent components to child components. This guide explains how props work, their immutability, setting default props, and how they enable the creation of dynamic and reusable UI components.



Understanding and Using Props in React Components

What are Props?

Props (short for "properties") are a way to pass data from a parent component to a child component in React. Think of them as read-only attributes that are passed into a component; they're similar to function arguments. You can use props to make your components more dynamic and reusable.

Passing Props

Props are passed to components as attributes in JSX. Inside the component, they are accessible through `this.props` (in class components) or directly as function arguments (in functional components).

Example: Passing a Name Prop

Passing Props Example (App.js)

import React from 'react';

const MyComponent = ({ name }) => (
  <p>Welcome to {name}</p>
);

const App = () => <MyComponent name="JavaTpoint" />;
export default App;

Immutability of Props

Props are immutable within the child component. You cannot directly modify the props passed to a component. If you need to change the data, you must do so in the parent component and then re-render the child component with updated props.

Default Props

You can set default values for props using the `defaultProps` static property on the component. This provides default values if the parent component doesn't explicitly pass a prop.

Default Props Example

MyComponent.defaultProps = {
  name: "JavaTpoint",
};

Combining State and Props

You can combine state and props within your components. The state manages internal data, while props provide data from parent components. This allows you to create components that are both dynamic and configurable.

Combining State and Props

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: 'Initial Name' };
  }

  render() {
    return <MyComponent jtpProp={this.state.name} />;
  }
}

const MyComponent = ({ jtpProp }) => (
  <p>Welcome to {jtpProp}</p>
);

Next Topic: React PropTypes Validation