DEV Community

Cover image for Learn React Concept 2
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

Learn React Concept 2

This is the continuation of the first Learn React Concept. Please check here to view the first one.


🎯 Concepts to cover

πŸ“‹ Conditional Rendering using the Logical && operator
πŸ“‹ Styling React Components
πŸ“‹ Form Handling
πŸ“‹ Fetching data from an API
πŸ“‹ Send request to server


Conditional Rendering

In the last tutorial, we used the ternary operator for our conditional rendering. Here is the same logic using the && operator.
Image description

In App.js

import './App.css';
import { Gender } from './components/Gender';

function App() {
  return (
    <div className="App">
      <Gender />
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

The result is:
Image description
If isMale equates to true, the expression after && will render.


Styling React Components

Styling allows us to beautify our Application
Create a file called Style.css and Styling.js in the component folder.

Styles.css

.main {
    color: rgb(42, 187, 28);
    background-color: black;
}
Enter fullscreen mode Exit fullscreen mode

Styling.js

import './Styles.css';
export const Styling = () => {
  return (
    <div>
      <h1 className="main">Learn style sheet</h1>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

App.js

import './App.css';
import { Styling } from './components/Styling';

function App() {
  return (
    <div className="App">
      <Styling />
    </div>
  );
}
export default App;

Enter fullscreen mode Exit fullscreen mode

The result is:
Image description


Inline styles

Another way of styling is the Inline Method. An inline style may be used to apply a unique style for a single element.
Image description

In App.js

import './App.css';
import { Inline } from './components/Inline';

function App() {
  return (
    <div className="App">
      <Inline />
    </div>
  );
}
export default App;

Enter fullscreen mode Exit fullscreen mode

Result is:
Image description


CSS Modules

These are CSS files in which all class names and animation names are scoped locally by default.
Image description
Image description

In App.js

import './App.css';
import { Module } from './components/Module';

function App() {
  return (
    <div className="App">
      <Module />
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Result:
Image description


Form Handling

Handling forms is about how you handle the data when it changes value or gets submitted.
Form.js

import { useState } from 'react';

export const Form = () => {
  const [username, setUsername] = useState('');
  console.log(username);

  const handleSubmit = (event) => {
    event.preventDefault(); // prevent page refresh
    alert(`Hello, welcome ${username}`);
  };
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Username</label>
        <input
          type="text"
          value={username}
          onChange={(event) => setUsername(event.target.value)}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

App.js

import './App.css';
import { Form } from './Form';

function App() {
  return (
    <div className="App">
      <Form />
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Result:
Image description


Fetching data from an API

_ The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object_
In Fetch.js

    import { useState, useEffect } from 'react';
    export const Fetch = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        fetch('https://fakestoreapi.com/products')
        .then((response) => response.json())
        .then((data) => setProducts(data))
        .catch((error) => console.log(error));
    }, []);
    return (
        <div>
        <h1>Products</h1>
        <ul>
            {products.map((product) => (
            <li key={product.id}>
                Title: {product.title}, Price:{product.price}, Rate: {product.rate}
            </li>
            ))}
        </ul>
        </div>
    );
    };
Enter fullscreen mode Exit fullscreen mode
import './App.css';
import { Fetch } from './components/Fetch';

function App() {
  return (
    <div className="App">
      <Fetch />
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Result:
Image description


Send request to server

Now that we have performed a get request, let's see how we can perform a Post request by sending data to the server.

Post.js

import { useState } from 'react';

export const PostForm = () => {
  const [image, setImage] = useState('');
  const [category, setCategory] = useState('');
  const [title, setTitle] = useState('');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');

  const submitHandler = (event) => {
    event.preventDefault();
    fetch('https://fakestoreapi.com/products', {
      method: 'POST',
      body: JSON.stringify({
        title: title,
        price: price,
        description: description,
        image: image,
        category: category,
      }),
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    })
      .then((response) => response.json())
      .then((json) => console.log(json));
  };
  return (
    <form onSubmit={submitHandler}>
      <div>
        <input
          type="text"
          name="description"
          placeholder="Description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
      </div>
      <div>
        <input
          type="text"
          name="title"
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
      </div>
      <div>
        <input
          type="text"
          name="price"
          placeholder="Price"
          value={price}
          onChange={(e) => setPrice(e.target.value)}
        />
      </div>
      <div>
        <input
          type="text"
          name="category"
          placeholder="Category"
          value={category}
          onChange={(e) => setCategory(e.target.value)}
        />
      </div>
      <div>
        <input
          type="text"
          name="image"
          placeholder="Image"
          value={image}
          onChange={(e) => setImage(e.target.value)}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

In App.js

import './App.css';
import { PostForm } from './components/Post';

function App() {
  return (
    <div className="App">
      <PostForm />
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Result:
Image description
Image description


Conclusion

I hope this hope was helpful in working with React. In the next post, we will put all these concepts together to build an app.
Thanks for reading.


Resources

Fake Store

Top comments (0)