Learn React Concept 2
Tags: react, javascript, tutorial, programming
Published: 2022-06-15 05:51:43

This is the continuation of the first Learn React Concept. Please check [here](https://dev.to/drsimplegraffiti/learn-react-concepts-54o0) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azr1ae5jsnjl3d0wa76e.png)

In `App.js`
```javascript
import './App.css';
import { Gender } from './components/Gender';

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

The result is:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmtnqfvghg5n4et0lrhs.png)
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;
}
```
`Styling.js`
```javascript
import './Styles.css';
export const Styling = () => {
  return (
    <div>
      <h1 className="main">Learn style sheet</h1>
    </div>
  );
};
```

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

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

```

The result is:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo7vz07z5zmpdb8m8yw1.PNG)

---

#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3d7g1qwwytx4dfpeu9su.png)

In `App.js`
```javascript
import './App.css';
import { Inline } from './components/Inline';

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

```

Result is:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89u9su5ye5wh65v360kw.PNG)

---

#### CSS Modules
These are CSS files in which all class names and animation names are scoped locally by default.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tn7njiglwadne92fmahn.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alrbrilolr3fqpni0hnc.png)

In `App.js`
```javascript
import './App.css';
import { Module } from './components/Module';

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

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xio77bzzpe21pe0ndfdq.PNG)
  

---

#### Form Handling
Handling forms is about how you handle the data when it changes value or gets submitted.
`Form.js`
```javascript
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>
  );
};
```

`App.js`
```javascript
import './App.css';
import { Form } from './Form';

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

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wiba4rm7x9gb5ofz7kr2.png)
 

---

#### 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`
```JavaScript
    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>
    );
    };
```

```JavaScript
import './App.css';
import { Fetch } from './components/Fetch';

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

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kyp4vgjdnl6vj2df654s.PNG)



---

#### 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`
```javascript
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>
  );
};
```

In `App.js`
```javascript
import './App.css';
import { PostForm } from './components/Post';

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

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os12o2e6nor0iu8whkhq.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abguftsvkgmgt3recd6i.png)

---

#### 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](https://fakestoreapi.com/docs)