Assignments Of Day 3: JSX - JavaScript XML

Rashmi Mishra
0

 Assignments Of Day 3: JSX - JavaScript XML 

Assignments: Working with JSX

Here are some assignments designed to practice JSX concepts with step-by-step solutions and explanations. Each task builds understanding in using JSX syntax, embedding JavaScript expressions, styling elements, and conditional rendering.


Assignment 1: Display a Personalized Greeting

Objective: Use JSX to display a greeting message that includes the user’s name.

Instructions:

1.  Create a React component called Greeting.

2.  Inside the component, create a variable called name and set it to a string (e.g., "Alice").

3.  Use JSX to display a message that says, "Hello, [name]!" where [name] is the value of the name variable.

Solution:

javascript

Copy code

import React from 'react';

 

function Greeting() {

  const name = "Alice"; // Define a variable with a name

 

  // Use JSX to display a greeting message

  return (

    <h1>Hello, {name}!</h1>

  );

}

 

export default Greeting;

Explanation:

  • We create a React function component Greeting.
  • Inside the component, we declare a variable name and assign it the value "Alice".
  • We use JSX to render the greeting message. The {name} in {} tells React to replace it with the variable’s value.

Assignment 2: Apply Inline Styling to Text

Objective: Add inline styles to text in JSX.

Instructions:

1.  Create a new component named StyledText.

2.  Inside this component, create an object textStyle to hold styling properties, e.g., color: 'blue' and fontSize: '24px'.

3.  Use the textStyle object to apply these styles to an <h1> element that displays "This text is styled!".

Solution:

javascript

Copy code

import React from 'react';

 

function StyledText() {

  const textStyle = {

    color: 'blue',       // Set text color

    fontSize: '24px'     // Set font size

  };

 

  return (

    <h1 style={textStyle}>This text is styled!</h1>

  );

}

 

export default StyledText;

Explanation:

  • We create a textStyle object containing CSS properties written in camelCase.
  • The style attribute in JSX expects an object, so we pass textStyle to it, applying these styles to the <h1> element.

Assignment 3: Display Conditional Message Using JSX

Objective: Use conditional rendering to display different messages based on a user’s login status.

Instructions:

1.  Create a component named WelcomeMessage.

2.  Inside the component, create a variable isLoggedIn and set it to true or false.

3.  Use JSX and a conditional (ternary) operator to display "Welcome back!" if isLoggedIn is true, or "Please log in." if it is false.

Solution:

javascript

Copy code

import React from 'react';

 

function WelcomeMessage() {

  const isLoggedIn = true; // Define a variable for login status

 

  return (

    <h1>{isLoggedIn ? "Welcome back!" : "Please log in."}</h1>

  );

}

 

export default WelcomeMessage;

Explanation:

  • We use the ternary operator {isLoggedIn ? "Welcome back!" : "Please log in."} within the JSX to decide what to display based on isLoggedIn.
  • If isLoggedIn is true, it displays "Welcome back!" Otherwise, it shows "Please log in."

Assignment 4: Create a List of Items with JSX

Objective: Use an array and JSX to dynamically generate a list.

Instructions:

1.  Create a component named ItemList.

2.  Inside the component, create an array items with a few strings, like ["Apple", "Banana", "Cherry"].

3.  Use JSX to render each item in an unordered list <ul>.

Solution:

javascript

Copy code

import React from 'react';

 

function ItemList() {

  const items = ["Apple", "Banana", "Cherry"]; // Array of items

 

  return (

    <ul>

      {items.map((item, index) => (

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

      ))}

    </ul>

  );

}

 

export default ItemList;

Explanation:

  • We use the map method to iterate over each item in the items array.
  • For each item, we create an <li> element with the item’s name. The key attribute is required for lists and is set to index for simplicity.

Assignment 5: Use Fragments to Group Elements Without Extra Nodes

Objective: Practice using React.Fragment to group multiple elements without adding extra nodes to the DOM.

Instructions:

1.  Create a component named UserInfo.

2.  Inside the component, add two elements, <h2> with "User Profile" and <p> with "This is the user profile section."

3.  Wrap both elements in a React.Fragment so that they don’t create an extra <div> or <section> in the DOM.

Solution:

javascript

Copy code

import React from 'react';

 

function UserInfo() {

  return (

    <React.Fragment>

      <h2>User Profile</h2>

      <p>This is the user profile section.</p>

    </React.Fragment>

  );

}

 

export default UserInfo;

Explanation:

  • By wrapping the elements in React.Fragment, we keep them in a single group without generating an unnecessary container in the final output.
  • This is useful for maintaining clean and efficient HTML structures.

Assignment 6: Render a Simple Component with Props

Objective: Create a component that accepts and displays props in JSX.

Instructions:

1.  Create a component named GreetingMessage that accepts a name prop.

2.  Display "Hello, [name]!" where [name] is the value passed as a prop.

3.  Render the GreetingMessage component in App.js and pass "Charlie" as the name prop.

Solution:

javascript

Copy code

// GreetingMessage.js

import React from 'react';

 

function GreetingMessage({ name }) {

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

}

 

export default GreetingMessage;

 

// In App.js

import React from 'react';

import GreetingMessage from './GreetingMessage';

 

function App() {

  return <GreetingMessage name="Charlie" />;

}

 

export default App;

Explanation:

  • The GreetingMessage component uses { name } to access the name prop directly.
  • We pass "Charlie" as the name prop when rendering GreetingMessage in App.js.

These assignments give students hands-on practice with JSX, helping them understand how to combine HTML-like syntax with JavaScript expressions and logic to create dynamic UI elements. Each step-by-step explanation breaks down how JSX operates, ensuring students gain a solid understanding of JSX basics.

4o

You said:

more

ChatGPT said:

ChatGPT

More JSX Assignments

These additional assignments will further reinforce JSX concepts, helping students practice embedding expressions, using props effectively, rendering lists with keys, handling conditional rendering, and managing component structure in React.


Assignment 7: Display Current Date and Time

Objective: Use JavaScript expressions in JSX to display the current date and time.

Instructions:

1.  Create a component called CurrentDateTime.

2.  Inside the component, use JavaScript's Date object to get the current date and time.

3.  Use JSX to display the message: "Today is [current date] and the time is [current time]."

Solution:

javascript

Copy code

import React from 'react';

 

function CurrentDateTime() {

  const currentDate = new Date();

  const date = currentDate.toLocaleDateString(); // Format date

  const time = currentDate.toLocaleTimeString(); // Format time

 

  return (

    <p>Today is {date} and the time is {time}.</p>

  );

}

 

export default CurrentDateTime;

Explanation:

  • We use Date object methods toLocaleDateString() and toLocaleTimeString() to get readable date and time formats.
  • JSX {} expressions allow us to embed these values in the output.

Assignment 8: Conditional Rendering with Multiple Conditions

Objective: Use multiple conditions to display a message based on a user's age.

Instructions:

1.  Create a component called UserStatus.

2.  Inside the component, create a variable age and set a value.

3.  Display a different message based on the age variable:

o    "You are a minor" if age is less than 18.

o    "You are an adult" if age is 18–60.

o    "You are a senior citizen" if age is greater than 60.

Solution:

javascript

Copy code

import React from 'react';

 

function UserStatus() {

  const age = 45; // Set user age

 

  return (

    <h2>

      {age < 18 ? "You are a minor" : age <= 60 ? "You are an adult" : "You are a senior citizen"}

    </h2>

  );

}

 

export default UserStatus;

Explanation:

  • We use a nested ternary operator for multiple conditions, with each condition returning a different message.
  • This demonstrates complex conditional logic directly in JSX.

Assignment 9: Render an Array of Objects as a Table

Objective: Create a table using an array of objects and render it in JSX.

Instructions:

1.  Create a component called ProductTable.

2.  Inside, define an array of objects where each object represents a product with properties name, price, and category.

3.  Use JSX to render this array as a table.

Solution:

javascript

Copy code

import React from 'react';

 

function ProductTable() {

  const products = [

    { name: 'Laptop', price: 1200, category: 'Electronics' },

    { name: 'Sofa', price: 450, category: 'Furniture' },

    { name: 'Shirt', price: 30, category: 'Clothing' }

  ];

 

  return (

    <table border="1">

      <thead>

        <tr>

          <th>Name</th>

          <th>Price</th>

          <th>Category</th>

        </tr>

      </thead>

      <tbody>

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

          <tr key={index}>

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

            <td>${product.price}</td>

            <td>{product.category}</td>

          </tr>

        ))}

      </tbody>

    </table>

  );

}

 

export default ProductTable;

Explanation:

  • We map over the products array and create a <tr> element for each product.
  • Using keys in the form of index ensures each row is uniquely identified, which helps React efficiently update the DOM.

Assignment 10: Render a Component with Default Props

Objective: Set default values for props in a component and render it.

Instructions:

1.  Create a component called UserProfile.

2.  Accept two props: name and age.

3.  Set default props to be name = "Guest" and age = "Not specified".

4.  Use JSX to display "User: [name]" and "Age: [age]".

Solution:

javascript

Copy code

import React from 'react';

 

function UserProfile({ name, age }) {

  return (

    <div>

      <h3>User: {name}</h3>

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

    </div>

  );

}

 

// Set default props

UserProfile.defaultProps = {

  name: 'Guest',

  age: 'Not specified'

};

 

export default UserProfile;

Explanation:

  • We assign default values to name and age using defaultProps, so if no props are passed, the component displays default text.

Assignment 11: Style Elements Conditionally with JSX

Objective: Use conditional styling based on props in a component.

Instructions:

1.  Create a component called Notification.

2.  Accept a prop status with possible values: "success", "error", and "warning".

3.  Apply a background color based on the status value:

o    Green for "success", red for "error", and yellow for "warning".

Solution:

javascript

Copy code

import React from 'react';

 

function Notification({ status }) {

  const style = {

    padding: '10px',

    color: 'white',

    backgroundColor:

      status === 'success' ? 'green' :

      status === 'error' ? 'red' :

      'yellow'

  };

 

  return (

    <div style={style}>

      This is a {status} message!

    </div>

  );

}

 

export default Notification;

Explanation:

  • We use a style object and apply conditional background colors based on the status prop.
  • Conditional styling helps dynamically adjust the appearance of elements based on data or state.

Assignment 12: Toggle Visibility with JSX and State

Objective: Create a button that toggles the visibility of text.

Instructions:

1.  Create a component called ToggleText.

2.  Use React’s useState hook to manage a visible state (initially true).

3.  Display a paragraph with the text "Hello, world!" only when visible is true.

4.  Add a button to toggle visible between true and false.

Solution:

javascript

Copy code

import React, { useState } from 'react';

 

function ToggleText() {

  const [visible, setVisible] = useState(true);

 

  return (

    <div>

      {visible && <p>Hello, world!</p>}

      <button onClick={() => setVisible(!visible)}>

        {visible ? "Hide" : "Show"} Text

      </button>

    </div>

  );

}

 

export default ToggleText;

Explanation:

  • We use useState to track visibility. {visible && <p>Hello, world!</p>} conditionally renders the paragraph.
  • The button toggles the visible state, dynamically updating the displayed text.

Assignment 13: Create a Simple Counter Using JSX and State

Objective: Implement a basic counter that increments and decrements.

Instructions:

1.  Create a component called Counter.

2.  Use useState to keep track of a count variable, initially set to 0.

3.  Render the current count and provide two buttons: "Increment" and "Decrement".

Solution:

javascript

Copy code

import React, { useState } from 'react';

 

function Counter() {

  const [count, setCount] = useState(0);

 

  return (

    <div>

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

      <button onClick={() => setCount(count + 1)}>Increment</button>

      <button onClick={() => setCount(count - 1)}>Decrement</button>

    </div>

  );

}

 

export default Counter;

Explanation:

  • We use useState to manage the count variable.
  • Clicking "Increment" increases count, and "Decrement" decreases it. {count} is embedded in JSX, so it updates automatically.

These assignments provide various scenarios to practice JSX and React’s core concepts, focusing on embedding expressions, managing props and state, conditional rendering, and styling. Each assignment encourages beginners to explore JSX's flexibility and see how it integrates with JavaScript to build dynamic user interfaces.


Tags

Post a Comment

0Comments

Post a Comment (0)