DEV Community

Cover image for React js review bagian 2
Andi Ismail
Andi Ismail

Posted on

React js review bagian 2

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
Enter fullscreen mode Exit fullscreen mode

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>
        )
    }
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Image 3gambar

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>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode
//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
Enter fullscreen mode Exit fullscreen mode

Image 3 hati berbeda

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>
    )
}
Enter fullscreen mode Exit fullscreen mode
//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

Enter fullscreen mode Exit fullscreen mode

Image function

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>
    )
}
Enter fullscreen mode Exit fullscreen mode
//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
Enter fullscreen mode Exit fullscreen mode

Image 4gambar


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

eg:



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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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

sekarang kita tahun nilai inputan kita berada di target dan value

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

Image nilainya langsung

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

const handleChangeText = (e)=>{
    //console.info(e.target.value)
    setText(e.target.value)
  }
Enter fullscreen mode Exit fullscreen mode

Image javascript

//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;

Enter fullscreen mode Exit fullscreen mode

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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

return
`

Image Fetch Api

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

//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>
  )
}

Enter fullscreen mode Exit fullscreen mode
//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;

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)