Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · React Basics and JSX
Interview question

What are Props in React? How do you pass data between components? React में Props क्या हैं? Components के बीच data कैसे pass करते हैं?

Answer
// Props are like function parameters
// They pass data from parent to child components

// Parent component
function App() {
    const user = { name: 'John', age: 25 };
    
    return (
        <div>
            <Welcome name='John' age={25} />
            <Welcome {...user} />
        </div>
    );
}

// Child component (Functional)
function Welcome(props) {
    return <h1>Hello, {props.name}! Age: {props.age}</h1>;
}

// OR using destructuring
function Welcome({ name, age }) {
    return <h1>Hello, {name}! Age: {age}</h1>;
}

// Class component with props
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

// Props are read-only (immutable)
// You cannot modify props directly

// Default props
function Greeting({ name = 'Guest' }) {
    return <h1>Hello, {name}</h1>;
}

// Or using defaultProps
Welcome.defaultProps = {
    name: 'Guest',
    age: 0
};

// PropTypes for type checking
import PropTypes from 'prop-types';

Welcome.propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number,
    email: PropTypes.string
};

// Passing functions as props
function Button({ onClick }) {
    return <button onClick={onClick}>Click me</button>;
}

function App() {
    const handleClick = () => alert('Clicked!');
    return <Button onClick={handleClick} />;
}

// Passing children as props
function Card({ children, title }) {
    return (
        <div className='card'>
            <h2>{title}</h2>
            <div>{children}</div>
        </div>
    );
}

<Card title='User Info'>
    <p>John Doe</p>
    <p>john@example.com</p>
</Card>
// Props - data parent से child को pass करते हैं
function Parent() {
    return <Child name='John' age={25} />;
}

function Child(props) {
    return <p>{props.name} is {props.age}</p>;
}

// Destructuring
function Child({ name, age }) {
    return <p>{name} is {age}</p>;
}

// Props immutable हैं - change नहीं कर सकते
// Default props
function Greeting({ name = 'Guest' }) {}

// PropTypes से type checking
Child.propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number
};

Was this answer clear?