React js review bagian 2
Published: 2022-11-16 04:25:14

Soal property,
Buatlah sebuah component dengan nama car yang mempunyai 1 properti dengan nama title dan content, component boleh d buat dengan class dan function ?

```
pnpm create vite
react_review_bag2
React
Javascript
cd react_review_bag2
pnpm install
pnpm run dev
```
buat component

```
//Card.jsx
import React from "react";

//class
export default class Card extends React.Component {
    constructor(props){
        super(props)
    }
    render(){
        return (
            <div>
                <img src="https://picsum.photos/seed/andi/200/200" alt="andi" />
                <h1>Ini hati </h1>
                <p>yang lama sudah tidak terisi.. sedih</p>
            </div>
        )
    }
}

```
selanjutnya kita panggil di App.jsx

```
//App.jsx

import './App.css'
import Card from './components/Card'
function App() {
  return (
    <div className='App'>
      <Card />
      <Card />
      <Card />

    </div> 
  )
}
export default App
```

![Image 3gambar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r73j8fa9qe0k8chesot1.png)

akan kita baut props, yang memuat data yang berbeda, kita akan 

```
Card.jsx

import React from "react";

//class
export default class Card extends React.Component {
    constructor(props){
        super(props)
    }
    render(){
        return (
            <div>
                <img src= {this.props.img} alt="andi" />
                <h1> {this.props.title} </h1>
                <p> {this.props.content} </p>
            </div>
        )
    }
}
```

```
//App.jsx

import './App.css'
import Card from './components/Card'
function App() {
  return (
    <div className='App'>
      <Card   img="https://picsum.photos/seed/andi/200/200" 
        title="Ini hati siapa" 
        content="Sudah lama tidak terisi? - Jone - 
      "/>
      <Card 
        img="https://picsum.photos/seed/ismail/200/200" 
        title="Ini hati kamu" 
        content="belum lama tidak terisi? - Jone - 
      "/>
      <Card 
      img="https://picsum.photos/seed/abdullah/200/200" 
        title="Ini hati dia" 
        content="akan lama tidak terisi? - Jone - 
      "/>
    </div>  
  )
}
export default App
```

![Image 3 hati berbeda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dzo4akvua6757u2p9a1.png)

selesai dengan class component, selanjtnya kita akan menggunakan cara kedua merender file jsx dengan functional component

```
//Card.jsx

//functional component
export default function Card(props){
    return (
        <div>
            <img src={props.img} alt={props.title} />
            <h1>{props.title}</h1>
            <p>{props.content}</p>
        </div>
    )
}
```

```
//App.jsx

import './App.css'
import Card from './components/Card'
function App() {
  return (
    <div className='App'>
      <Card 
       img="https://picsum.photos/seed/andi/200/200" 
        title="Ini hati siapa" 
        content="Sudah lama tidak terisi? - Jone - 
      "/>
      <Card 
        img="https://picsum.photos/seed/ismail/200/200" 
        title="Ini hati kamu" 
        content="belum lama tidak terisi? - Jone - 
      "/>
      <Card   img="https://picsum.photos/seed/abdullah/200/200" 
        title="Ini hati dia" 
        content="akan lama tidak terisi? - Jone - 
      "/>
    </div>
  )
}
export default App

```

![Image function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8yicfsefvhd7posvf19.png)

props diatas Card.jsx adalah objek sehingga kita akan menyingkat dengan melakukan destruct

```
//Card.jsx

//functional component
export default function Card({ img, title, content }){
    return (
        <div>
            <img src={img} alt={title} />
            <h1>{title}</h1>
            <p>{content}</p>
        </div>
    )
}
```

```
//App.jsx

import './App.css'
import Card from './components/Card'
function App() {
  return (
    <div className='App'>

      <Card 
        img="https://picsum.photos/seed/andi/200/200" 
        title="Ini hati siapa" 
        content="Sudah lama tidak terisi? - Jone - 
      "/>
      <Card 
        img="https://picsum.photos/seed/ismail/200/200" 
        title="Ini hati kamu" 
        content="belum lama tidak terisi? - Jone - 
      "/>
      <Card 
        img="https://picsum.photos/seed/abdullah/200/200" 
        title="Ini hati dia" 
        content="akan lama tidak terisi? - Jone - 
      "/>
      <Card 
        img={'https://picsum.photos/seed/abduh/200/200'}
        title={'Atas Neraka'}
        content={'Bawah Surga'}
      />
    </div>
  )
}
export default App
```

![Image 4gambar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydh15o34tsogy1g3sx7b.png)

---

Soal nomer 2,
Buatlah sebuah komponent layout, dimana komponent tersebut bisa di isi dengan komponent lainnya..

eg:
<Layout>
 <Card .../>
</Layout>
boleh menggunakan properti biasa atau menggunakan property children.

kita buat MainLayout.jsx

```
//MainLayout.jsx

import React from "react";
export default function MainLayout({children}){
    return (
        <main>
            {children}
        </main>
    )
}
```
masukkan main layout sebagai pembungkus card

```
//App.jsx

import "./App.css";
import Card from "./components/Card";
import MainLayout from "./layouts/MainLayout";

function App() {
  return (
    //<div className='App'>
    <MainLayout>
      <Card
        img="https://picsum.photos/seed/andi/200/200"
        title="Ini hati siapa"
        content="Sudah lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/ismail/200/200"
        title="Ini hati kamu"
        content="belum lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/abdullah/200/200"
        title="Ini hati dia"
        content="akan lama tidak terisi? - Jone - 
      "
      />
      <Card img={"https://picsum.photos/seed/abduh/200/200"} title={"Atas Neraka"} content={"Bawah Surga"} />
    </MainLayout>
    //</div>
  );
}
export default App;

```

---

Soal state
Buatlah sebuah element h1 dan input setiap input di isi dengan value (diubah) maka konten pada h1 juga ikut berubah (State)?
 
berarti kita buat state dulu, 

`
//state 
  const [text, setText]=useState("ubah disini")
`
kita tampilkan disini
`<h1>{text}</h1>
      <div>
        <input type="text" onChange={handleChangeText} />
      </div>`
kita buat function penangkap valuenya 
` const handleChangeText = (e)=>{
    console.info(e)
  }`

![Image target value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aovrhatdwjza1cczrvyo.png)

sekarang kita tahun nilai inputan kita berada di target dan value

`const handleChangeText = (e)=>{
    console.info(e.target.value)
  }`

![Image nilainya langsung](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0ykmvyazu04yyafmvbf.png)

di console berhasil manangkap valuenya sekarang, console.info kita ganti dengan setText

```
const handleChangeText = (e)=>{
    //console.info(e.target.value)
    setText(e.target.value)
  }
```

![Image javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p513k0jyrbgk7i9t7iig.png)

```
//App.jsx

import "./App.css";
import Card from "./components/Card";
import MainLayout from "./layouts/MainLayout";
import {useState} from "react" 

function App() {

  //state 
  const [text, setText]=useState("ubah disini")

  //function yang menangkap value dari element input
  const handleChangeText = (e)=>{
    //console.info(e.target.value)
    setText(e.target.value)
  }

  return (
    //<div className='App'>
    <MainLayout>

      <h1>{text}</h1>
      <div>
        <input type="text" onChange={handleChangeText} />
      </div><br /><br />

      <Card
        img="https://picsum.photos/seed/andi/200/200"
        title="Ini hati siapa"
        content="Sudah lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/ismail/200/200"
        title="Ini hati kamu"
        content="belum lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/abdullah/200/200"
        title="Ini hati dia"
        content="akan lama tidak terisi? - Jone - 
      "
      />
      <Card img={"https://picsum.photos/seed/abduh/200/200"} title={"Atas Neraka"} content={"Bawah Surga"} />
    </MainLayout>
    //</div>
  );
}
export default App;

```

---
soal conditional rendering 
kita tau kalau kompnent card kita sudah memiliki props img, yang berisi source dari gambar. apa yang terajdi apabila programer lupa mengisi props image ? tentunya muncul icon gamabr error.

seilahkan fixed bug ini dengan conditional rendering artinya element img hanya akan terrender ketika ada data di props img.

`{img ? <img src={img} alt={title} /> : null }`

---
soal fetching data
silahkan ambi data dari sebuah api end point  https://jsonplaceholder.typicode.com/posts dan render menggunakan component card

note cara bebas, bisa menggunakan axios, fetch : 

- ract-query nilai plus
- custom hook nilai plus

Jawabannya : 
kita buat Fetchapi.jsx

```
import React from 'react'
import { useState, useEffect } from 'react'

export default function FetchApi() {

    const [post, setPost]= useState();

    const getPost = async()=>{
        try{
            const result = await fetch("https://jsonplaceholder.typicode.com/posts")
            const data = await result.json();
            return data
        }
        catch (error){
            console.error(error)
        }
    }

    //useeeffect
    useEffect(()=>{
        getPost()
        .then((res)=>{setPost(res)})
        .catch((err)=>{console.error(err)})
    }, [])
  return (
    <div>
       <h1>Fetch Api</h1>
       {post.map((e)=>(
            <div key={e.id}>
                <h3>{e.title}</h3>
                <p>{e.body}</p>
            </div>
       ))} 
    </div>
  )
}

```
selanjutnya kita import ke dalam App.jsx
`import FetchApi from "./components/FetchApi";

return <FetchApi />
`

![Image Fetch Api](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c9g7vf2hgzog7al3fz3l.png)

ada beberapa cara menghandle error conditional rendering diantaranya : 
Tambahkan array
`const [post, setPost]= useState([]);`

atau tambahkan if
`if(!post){
  return <p>loading...</p>
}
`

atau bisa juga post?.
`{post?.map((e)=>(`


![Image fetching data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgygli2csktehmkro8i3.png)

```
//FetchApi.jsx

import React from 'react'
import { useState, useEffect } from 'react'

export default function FetchApi() {

    const [post, setPost]= useState([]);

    const getPost = async()=>{
        try{
            const result = await fetch("https://jsonplaceholder.typicode.com/posts")
            const data = await result.json();
            return data
        }
        catch (error){
            console.error(error)
        }
    }

    //useeeffect
    useEffect(()=>{
        getPost()
        .then((res)=>{setPost(res)})
        .catch((err)=>{console.error(err)})
    }, [])
  return (
    <div>
       <h1>Fetch Api</h1>
       {post.map((e)=>(
            <div key={e.id}>
                <h3>{e.title}</h3>
                <p>{e.body}</p>
            </div>
       ))} 
    </div>
  )
}

```

```
//App.jsx

import "./App.css";
import Card from "./components/Card";
import MainLayout from "./layouts/MainLayout";
import {useState} from "react" 
import FetchApi from "./components/FetchApi";

function App() {

  //state 
  const [text, setText]=useState("ubah disini")

  //function yang menangkap value dari element input
  const handleChangeText = (e)=>{
    //console.info(e.target.value)
    setText(e.target.value)
  }

  return (
    //<div className='App'>
    <MainLayout>
      <FetchApi />
      
      
      
      <br /><br />
      <h1>{text}</h1>
      <div>
        <input type="text" onChange={handleChangeText} />
      </div><br /><br />

      <Card
        img="https://picsum.photos/seed/andi/200/200"
        title="Ini hati siapa"
        content="Sudah lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/ismail/200/200"
        title="Ini hati kamu"
        content="belum lama tidak terisi? - Jone - 
      "
      />
      <Card
        img="https://picsum.photos/seed/abdullah/200/200"
        title="Ini hati dia"
        content="akan lama tidak terisi? - Jone - 
      "
      />
      <Card img={"https://picsum.photos/seed/abduh/200/200"} title={"Atas Neraka"} content={"Bawah Surga"} />
    </MainLayout>
    //</div>
  );
}
export default App;

```
Terimkasih. 
https://github.com/andiks2018/JvalleyReact-reviewBag2.git