React Lecture 2: Props, Multiple Articles, ArticleList Component and UseState intro - MantsSk/CA_PTUA14 GitHub Wiki

Lecture 2: Props, Multiple Articles, ArticleList Component

Welcome to the second lecture in our full-stack news website course! In this lecture, we'll explore:

  1. Props: How to pass dynamic data to components.
  2. Rendering Multiple Articles: Display multiple news articles dynamically.
  3. ArticleList Component: A custom component to manage multiple articles.
  4. More CSS Styling: Enhancing the UI

1. Understanding Props in React

Props (short for properties) allow us to pass data from a parent component to a child component. This makes components more reusable and dynamic.

Example of Using Props:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Props work similarly to function parameters. They allow us to customize component behavior based on the data we pass.

Applying Props to Our Article Component

In the previous lecture, we created a static Article component. Now, we'll modify it to accept props for the title and content.

Modify src/components/Article.js:

import React from 'react';
import './Article.css';

function Article({ title, content }) {
  return (
    <article className="article">
      <h2>{title}</h2>
      <p>{content}</p>
    </article>
  );
}

export default Article;

Now, when rendering <Article />, we must provide title and content as props.


2. Rendering Multiple Articles

Instead of displaying a single article, we’ll create multiple articles dynamically using an array of objects.

Create an Article List

We'll store multiple article objects in an array and map over them to render multiple Article components.

Create src/components/ArticleList.js:

import React from 'react';
import Article from './Article';
import './ArticleList.css';

function ArticleList() {
  const articles = [
    { title: "React 101: Getting Started", content: "Learn the basics of React, a powerful UI library." },
    { title: "Understanding JSX", content: "JSX is a syntax extension for JavaScript that allows writing HTML in React." },
    { title: "Component Reusability in React", content: "Building modular components improves scalability and maintainability." }
  ];

  return (
    <div className="article-list">
      {articles.map((article, index) => (
        <Article key={index} title={article.title} content={article.content} />
      ))}
    </div>
  );
}

export default ArticleList;

Explanation:

  • We store multiple articles in an array.
  • We use the .map() function to iterate over the array and create multiple Article components.
  • The key prop (required in lists) helps React track list items efficiently.

3. Integrating ArticleList into App.js

Now, let's update our App.js to display the list of articles instead of a single article.

Modify src/App.js:

import React from 'react';
import Header from './components/Header';
import ArticleList from './components/ArticleList';
import Footer from './components/Footer';
import './App.css';

function App() {
  return (
    <div className="App">
      <Header />
      <main>
        <ArticleList />
      </main>
      <Footer />
    </div>
  );
}

export default App;

Now, the app will dynamically render multiple articles using ArticleList.


4. Adding Click Counter To State in our Article

To add interactivity, we’ll enhance our Article component by adding a basic state that counts clicks. In React, state is an object that holds data specific to a component and can change over time. When state updates, React re-renders the component to reflect the change.

Follow these steps:

Import the useState Hook: Begin by importing useState from React.

import React, { useState } from 'react';

Initialize the State: Inside the component, initialize a state variable named clickCount with an initial value of 0. The state will have a method setClickCount which will update the value of clickCount.

  const [clickCount, setClickCount] = useState(0);

Handle Click Events: Create a function (handleArticleClick) that updates the state by incrementing clickCount when the article is clicked.

  // Increment the click count each time the article is clicked
  const handleArticleClick = () => {
    setClickCount(prevCount => prevCount + 1);
  };

Display the Click Count: Render the current click count in the UI, so users see how many times the article has been clicked.

      <p>Clicked: {clickCount} times</p>

Full code:

import React, { useState } from 'react';
import './Article.css';

function Article({ title, content }) {
  // Declare a state variable for the click count, starting at 0
  const [clickCount, setClickCount] = useState(0);

  // Increment the click count each time the article is clicked
  const handleArticleClick = () => {
    setClickCount(prevCount => prevCount + 1);
  };

  return (
    <article className="article" onClick={handleArticleClick}>
      <h2>{title}</h2>
      <p>{content}</p>
      <p>Clicked: {clickCount} times</p>
    </article>
  );
}

export default Article;

Explanation:

State in React: Unlike props (which are passed in), state is managed within the component. It holds dynamic data—in this case, the number of times an article is clicked. When you call setClickCount, React automatically re-renders the component to show the updated count.

Event Handling: The onClick event is attached to the

element. Each click triggers the handleArticleClick function, which increases the clickCount by one.

4. CSS Styling

To make the articles look better, we'll add more styles to Article.css and ArticleList.css.

Modify src/components/Article.css:

.article {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin: 10px 0;
  width: 80%;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
}

.article h2 {
  color: #333;
}

.article p {
  color: #666;
  font-size: 16px;
}

Create src/components/ArticleList.css:

.article-list {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

Styling Concepts Used:

  • Box Shadows: Added a shadow to each article for a card-like effect.
  • Flexbox Layout: Centering articles within the article-list container.

Practical Exercise

1st exercise

Improve your application according to what we did in lecture

2nd exercise

Modify Article.js to include a button that toggles a liked state using useState.

The button should display "Like" when not liked and "Unlike" when liked.

Optionally, adjust the article styling based on its liked state.

3rd exercise

  • Modify Article.js to accept an imageUrl prop and display an optional image.
  • Add more styles to improve the look of the news list.
  • Experiment by adding more articles to ArticleList.
⚠️ **GitHub.com Fallback** ⚠️