Ricardo de Paula
Ricardo de Paula

Reputation: 632

How to pass data to a single component

Sometimes it makes you want to give up. Things that seem so simple to solve turn into a big problem.

I'm work on https://rickandmortyapi.com/ and I'm using react-router-dom.

I had created a list of all characters:

import React, { useState, useEffect } from 'react'
// styles
import { Wrapper, CardGrid, Grid, GridInfo } from './Cards.styles'
// API functions
import { getCharacters } from '../../API'

// import Link from react-router-dom
import { Link } from 'react-router-dom'

const Cards = () => {
  // state to keep track of the characters
  const [characters, setCharacters] = useState([])
  // state to keep track of character
  const [character, setCharacter] = useState([])

  // function to get the characters from the API
  const getCharactersFromAPI = async () => {
    try {
      const response = await getCharacters()
      setCharacters(response.results)
      return response
    } catch (error) {
      console.log(error)
    }
  }

  // function to get the single character from the API

  // const getCharacterFromAPI = async () => {
  //   try {
  //     const response = await getCharacter()
  //     setCharacter(response.results)
  //     return response
  //   } catch (error) {
  //     console.log(error)
  //   }
  // }

  // useeffect to update the characters
  useEffect(() => {
    getCharactersFromAPI()
    // getCharacterFromAPI()
  }, [])

  return (
    <Wrapper>
      <CardGrid>
        {characters.map((character) => {
          const {
            id,
            name,
            image,
            species,
            gender,
            // destucturing an object inside an array
            location,
          } = character
          return (
            <Grid key={id}>
              <img src={image} alt={name} />
              <GridInfo character={character}>
                <Link to={`/character/${id}`}>{name}</Link>
                <p className='first'>{species}</p>
                <p>{gender}</p>
                <p>{location.name}</p>
              </GridInfo>
            </Grid>
          )
        })}
      </CardGrid>
    </Wrapper>
  )
}
export default Cards

My API.js

// get all characters
export const getCharacters = async () => {
  return await fetch('https://rickandmortyapi.com/api/character')
    .then((response) => response.json())
    .then((json) => {
      ////   console.log(json)
      return json
    })
}

// Get a single character
export const getCharacter = async (id) => {
  return await fetch(`https://rickandmortyapi.com/api/character/${id}`)
    .then((response) => response.json())
    .then((json) => {
      ////   console.log(json)
      return json
    })
}

And I had created a SingleCharacter component to display each character based on your id.

SingleCharacter:

import React from 'react'
import { Wrapper } from './SingleCharacter.styles'

// show single character

const SingleCharacter = ({ character }) => (
  <Wrapper>
    <h1>Single</h1>
  </Wrapper>
)

export default SingleCharacter

I dont Know how to make this component works.

Upvotes: 0

Views: 52

Answers (1)

Siddhesh Dabholkar
Siddhesh Dabholkar

Reputation: 168

in your app.js file import SingleCharacter

//app.js

<Router>
//other routes
<Route exact path="/character/:characterId" component={SingleCharacter} />
</Router>

In your SingleCharacter file

import {useState,useEffect} from 'react';
import {useParams} from "react-router-dom";
import { Wrapper } from './SingleCharacter.styles'


// show single character
const SingleCharacter=()=>{
const [character,setCharacter]=useState(null);
const {characterId}=useParams();
useEffect(()=>{
fetch(`https://rickandmortyapi.com/api/character/${characterId}`)
    .then((response) => response.json())
    .then((json) => {
      console.log(json);
      setCharacter(json);
    })
},[])
return(
 <Wrapper>
    <h1>Single</h1>
  </Wrapper>
)
}

export default SingleCharacter

Upvotes: 1

Related Questions