Assignments of Day 5: Components and Props in React

Rashmi Mishra
0

 Assignments of Day 5: Components and Props in React

Assignment 1: Creating a Greeting Component

Problem:

Create a functional component named Greeting that accepts a name as a prop and displays a greeting message like: "Hello, [name]!" where [name] is passed as a prop from the parent component.

Step-by-Step Solution:

1.  Create a new file called Greeting.js and write the Greeting functional component.

o    This component will take props as an argument and display a message using the name prop.

2.  Create the parent component in App.js.

o    In this component, pass a name as a prop to the Greeting component.

Solution:

javascript

Copy code

// Greeting.js (Child Component)

import React from 'react';

 

// Greeting component that accepts 'name' prop

function Greeting(props) {

  return <h1>Hello, {props.name}!</h1>;

}

 

export default Greeting;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import Greeting from './Greeting'; // Import Greeting component

 

// App component that passes 'name' as a prop to Greeting

function App() {

  return (

    <div>

      <Greeting name="Alice" /> {/* Passing name prop */}

    </div>

  );

}

 

export default App;

Explanation:

  • In Greeting.js, we defined a functional component Greeting that uses the props argument to access the name prop.
  • The parent component App.js imports Greeting and passes the value "Alice" as the name prop to it.
  • When rendered, the Greeting component displays "Hello, Alice!".

Assignment 2: Passing Multiple Props to a Child Component

Problem:

Create a functional component UserProfile that accepts name, age, and location as props and displays them.

Step-by-Step Solution:

1.  Create a file called UserProfile.js for the child component.

o    This component will accept name, age, and location as props and display them in a paragraph format.

2.  In the parent component, pass values for name, age, and location to the UserProfile component.

Solution:

javascript

Copy code

// UserProfile.js (Child Component)

import React from 'react';

 

// UserProfile component that accepts 'name', 'age', and 'location' as props

function UserProfile(props) {

  return (

    <div>

      <h2>User Profile</h2>

      <p>Name: {props.name}</p>

      <p>Age: {props.age}</p>

      <p>Location: {props.location}</p>

    </div>

  );

}

 

export default UserProfile;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import UserProfile from './UserProfile'; // Import UserProfile component

 

// App component passing multiple props

function App() {

  return (

    <div>

      <UserProfile name="John" age={30} location="New York" />

    </div>

  );

}

 

export default App;

Explanation:

  • UserProfile is a functional component that receives three props: name, age, and location.
  • In App.js, we pass "John", 30, and "New York" as props to the UserProfile component.
  • The UserProfile component then renders these props in paragraphs.

Assignment 3: Passing an Array as a Prop

Problem:

Create a HobbiesList component that accepts an array of hobbies as a prop and displays each hobby in an unordered list (<ul>).

Step-by-Step Solution:

1.  Create a file called HobbiesList.js for the child component.

o    This component will accept an array of hobbies and display each hobby as an item in a list.

2.  In the parent component, pass an array of hobbies to the HobbiesList component.

Solution:

javascript

Copy code

// HobbiesList.js (Child Component)

import React from 'react';

 

// HobbiesList component accepts 'hobbies' array as a prop

function HobbiesList(props) {

  return (

    <div>

      <h2>Hobbies</h2>

      <ul>

        {props.hobbies.map((hobby, index) => (

          <li key={index}>{hobby}</li>

        ))}

      </ul>

    </div>

  );

}

 

export default HobbiesList;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import HobbiesList from './HobbiesList'; // Import HobbiesList component

 

// App component passing an array of hobbies

function App() {

  const hobbies = ['Reading', 'Cooking', 'Traveling', 'Cycling']; // Array of hobbies

 

  return (

    <div>

      <HobbiesList hobbies={hobbies} /> {/* Passing hobbies array as prop */}

    </div>

  );

}

 

export default App;

Explanation:

  • HobbiesList receives a prop called hobbies, which is an array of strings.
  • Inside HobbiesList, we use JavaScript's map() method to iterate over the array and display each hobby inside a <li> tag.
  • The parent component App passes the hobbies array to HobbiesList as a prop.

Assignment 4: Passing Functions as Props

Problem:

Create a button component IncrementButton that accepts a function onClick as a prop. This function should be called when the button is clicked. In the parent component, implement the function to increment a counter value and pass it to the button component.

Step-by-Step Solution:

1.  Create the IncrementButton component which will accept an onClick function as a prop and trigger it when clicked.

2.  Create a parent component that holds a counter state and passes the increment function to IncrementButton as a prop.

Solution:

javascript

Copy code

// IncrementButton.js (Child Component)

import React from 'react';

 

// IncrementButton component that accepts 'onClick' function as a prop

function IncrementButton(props) {

  return <button onClick={props.onClick}>Increment</button>;

}

 

export default IncrementButton;

javascript

Copy code

// App.js (Parent Component)

import React, { useState } from 'react';

import IncrementButton from './IncrementButton'; // Import IncrementButton component

 

// App component with counter state

function App() {

  const [count, setCount] = useState(0); // State to hold the counter

 

  // Increment function

  const incrementCount = () => {

    setCount(count + 1); // Increment count by 1

  };

 

  return (

    <div>

      <h1>Count: {count}</h1>

      {/* Passing incrementCount function as a prop to IncrementButton */}

      <IncrementButton onClick={incrementCount} />

    </div>

  );

}

 

export default App;

Explanation:

  • The IncrementButton component accepts an onClick function as a prop and calls it when the button is clicked.
  • The App component holds a counter state using the useState hook. It defines the incrementCount function to update the counter value.
  • The incrementCount function is passed to IncrementButton as the onClick prop.
  • When the button is clicked, the incrementCount function is invoked, incrementing the counter value.

Assignment 5: Displaying User Information Using Props

Problem:

Create a UserCard component that displays the name, email, and phone number of a user, which are passed as props from the parent component.

Step-by-Step Solution:

1.  Create the UserCard component that will accept name, email, and phone as props.

2.  In the parent component, pass these values to the UserCard component.

Solution:

javascript

Copy code

// UserCard.js (Child Component)

import React from 'react';

 

// UserCard component that accepts 'name', 'email', and 'phone' as props

function UserCard(props) {

  return (

    <div>

      <h2>User Information</h2>

      <p>Name: {props.name}</p>

      <p>Email: {props.email}</p>

      <p>Phone: {props.phone}</p>

    </div>

  );

}

 

export default UserCard;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import UserCard from './UserCard'; // Import UserCard component

 

// App component passing user information as props

function App() {

  return (

    <div>

      <UserCard name="Jane Doe" email="jane.doe@example.com" phone="123-456-7890" />

    </div>

  );

}

 

export default App;

Explanation:

  • The UserCard component receives name, email, and phone as props and displays them inside paragraph tags.
  • The parent component App passes the corresponding values as props to the UserCard component.

Conclusion

These assignments provide a hands-on approach to understanding how to:

  • Create functional components.
  • Pass data between parent and child components using props.
  • Pass different data types such as strings, arrays, and functions as props.

Practice these assignments to build a strong foundation in React component architecture!

4o mini

You said:

some more

ChatGPT said:

ChatGPT

Assignment 6: Conditional Rendering with Props

Problem:

Create a Message component that displays either a welcome message or an error message based on the isLoggedIn prop. If the user is logged in, display "Welcome, [username]!", otherwise display "Please log in."

Step-by-Step Solution:

1.  Create the Message component that accepts a prop isLoggedIn and conditionally renders either a welcome message or a log-in prompt.

2.  In the parent component, pass the value of isLoggedIn and username to the Message component.

Solution:

javascript

Copy code

// Message.js (Child Component)

import React from 'react';

 

function Message(props) {

  if (props.isLoggedIn) {

    return <h1>Welcome, {props.username}!</h1>;

  } else {

    return <h1>Please log in.</h1>;

  }

}

 

export default Message;

javascript

Copy code

// App.js (Parent Component)

import React, { useState } from 'react';

import Message from './Message'; // Import Message component

 

function App() {

  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const [username, setUsername] = useState('John Doe');

 

  return (

    <div>

      <Message isLoggedIn={isLoggedIn} username={username} />

      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>

        Toggle Login Status

      </button>

    </div>

  );

}

 

export default App;

Explanation:

  • In the Message component, we check the isLoggedIn prop to conditionally render either a welcome message or a login prompt.
  • In App.js, we maintain the isLoggedIn state and a username state. The isLoggedIn state is toggled when the button is clicked.
  • We pass both isLoggedIn and username as props to the Message component.

Assignment 7: Styling Components Using Props

Problem:

Create a StyledButton component that accepts two props: label (the button text) and color (the button background color). The button should display the label and have the background color set to the value passed via the color prop.

Step-by-Step Solution:

1.  Create the StyledButton component that accepts label and color as props.

o    Set the button's background color using the color prop.

o    Display the label as the button text.

2.  In the parent component, pass the label and color props to the StyledButton.

Solution:

javascript

Copy code

// StyledButton.js (Child Component)

import React from 'react';

 

function StyledButton(props) {

  const buttonStyle = {

    backgroundColor: props.color,

    padding: '10px 20px',

    border: 'none',

    color: 'white',

    fontSize: '16px',

    cursor: 'pointer',

  };

 

  return <button style={buttonStyle}>{props.label}</button>;

}

 

export default StyledButton;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import StyledButton from './StyledButton'; // Import StyledButton component

 

function App() {

  return (

    <div>

      <StyledButton label="Click Me" color="blue" />

      <StyledButton label="Submit" color="green" />

    </div>

  );

}

 

export default App;

Explanation:

  • The StyledButton component accepts label and color props.
  • The color prop is used to dynamically set the button's background color using inline styles.
  • The parent component App passes different label and color props to create two different buttons.

Assignment 8: Handling Input Changes via Props

Problem:

Create a TextInput component that accepts a value prop and an onChange function. The TextInput component should update the parent component's state when the input value changes.

Step-by-Step Solution:

1.  Create the TextInput component that accepts a value prop and an onChange function. The input field should reflect the value passed as a prop and call the onChange function whenever the input value changes.

2.  In the parent component, maintain the input value in state and pass it along with the onChange function to the TextInput component.

Solution:

javascript

Copy code

// TextInput.js (Child Component)

import React from 'react';

 

function TextInput(props) {

  return (

    <input

      type="text"

      value={props.value}

      onChange={props.onChange}

      placeholder="Type something"

    />

  );

}

 

export default TextInput;

javascript

Copy code

// App.js (Parent Component)

import React, { useState } from 'react';

import TextInput from './TextInput'; // Import TextInput component

 

function App() {

  const [inputValue, setInputValue] = useState('');

 

  const handleInputChange = (event) => {

    setInputValue(event.target.value); // Update the state with the input value

  };

 

  return (

    <div>

      <TextInput value={inputValue} onChange={handleInputChange} />

      <p>You typed: {inputValue}</p>

    </div>

  );

}

 

export default App;

Explanation:

  • The TextInput component receives value and onChange as props. It uses the value to reflect the input and calls onChange when the value changes.
  • The App component maintains the inputValue state and provides a handleInputChange function to update this state.
  • The App passes both inputValue and handleInputChange as props to TextInput.

Assignment 9: Using Default Props

Problem:

Create a Card component that displays a title, content, and an optional image. If no image is passed, display a default image. Use default props to set the default value for the image prop.

Step-by-Step Solution:

1.  Create the Card component that accepts title, content, and image as props. Set a default value for the image prop.

2.  In the parent component, pass only title and content props, leaving image empty to test the default image.

Solution:

javascript

Copy code

// Card.js (Child Component)

import React from 'react';

 

function Card(props) {

  return (

    <div>

      <h2>{props.title}</h2>

      <p>{props.content}</p>

      <img src={props.image} alt="Card" style={{ width: '200px' }} />

    </div>

  );

}

 

Card.defaultProps = {

  image: 'https://via.placeholder.com/200', // Default image URL

};

 

export default Card;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import Card from './Card'; // Import Card component

 

function App() {

  return (

    <div>

      <Card title="My Card" content="This is a description of the card." />

    </div>

  );

}

 

export default App;

Explanation:

  • In the Card component, we use Card.defaultProps to specify a default value for the image prop.
  • If the parent component doesn't pass the image prop, the default image (https://via.placeholder.com/200) will be used.
  • In the parent component, we only pass the title and content props, which will trigger the default image.

Assignment 10: List Rendering with Props

Problem:

Create a ProductList component that accepts an array of products as a prop. Each product has a name, price, and description. Display the products in a list format.

Step-by-Step Solution:

1.  Create the ProductList component that accepts an array of products and renders each product's information in an unordered list.

2.  In the parent component, pass the products array to the ProductList component.

Solution:

javascript

Copy code

// ProductList.js (Child Component)

import React from 'react';

 

function ProductList(props) {

  return (

    <div>

      <h2>Product List</h2>

      <ul>

        {props.products.map((product, index) => (

          <li key={index}>

            <h3>{product.name}</h3>

            <p>Price: ${product.price}</p>

            <p>{product.description}</p>

          </li>

        ))}

      </ul>

    </div>

  );

}

 

export default ProductList;

javascript

Copy code

// App.js (Parent Component)

import React from 'react';

import ProductList from './ProductList'; // Import ProductList component

 

function App() {

  const products = [

    { name: 'Product 1', price: 30, description: 'This is a great product.' },

    { name: 'Product 2', price: 50, description: 'This product is amazing.' },

    { name: 'Product 3', price: 70, description: 'Best product in the market.' },

  ];

 

  return (

    <div>

      <ProductList products={products} />

    </div>

  );

}

 

export default App;

Explanation:

  • The ProductList component receives an array of products as a prop and uses .map() to render each product's details in a list.
  • The App component defines an array of products and passes it to the ProductList component.

Tags

Post a Comment

0Comments

Post a Comment (0)