React component array with Typescript(.tsx)

Asked

Viewed 81 times

0

I have a small project using Next.js, React and Typescript.

The idea is that a set of values within an array in a . json file be transformed into the React components and placed on the page afterwards.

tsx component.:

import styles from '../styles/BlocoTarefa.module.css'

interface Tarefa {
    materia: string,
    local: string,
    descricao: string,
    data: string,
}

export default function BlocoTarefa(props: Tarefa) {
    return(
        <div className={styles.tarefaContainer}>
            <div className={styles.left}>
                <div>Matéria: {props.materia}</div>
                <div>Atividade: {props.descricao}</div>
                <div><span>Local de envio: {props.local}</span><span className={styles.data}>Data de Entrega: {props.data}</span></div>
            </div>
            <div>
                <input type="checkbox" id="cbx" className={styles.cbx} />
                <label htmlFor="cbx" className={styles.check}>
                     check
                </label>
            </div>
        </div>
    )
}

data json.

[
    {
        "materia": "LPI",
        "local": "AVA",
        "descricao": "Entrada e saída de dados",
        "data": "04/03"
    },
    {
        "materia": "MAT",
        "local": "EMAIL",
        "descricao": "Resolver e enviar",
        "data": "04/03"
    }
]

currently the folder structure is like this: (I’m not good at typing this, sorry)

Projeto
|
|-- Public
|      |
|      |-- data.json
|
|
src -- components -- componente.tsx
|
|
pages -- index.tsx

I’m having difficulties mainly in loading the json.

  • 1

    What is your doubt?

  • how to do this

1 answer

0


import React, { useState, useEffect } from 'react'
import Data from 'data.json'

interface Tarefa {
  materia: string,
  local: string,
  descricao: string,
  data: string
}

interface TarefaProps {
  tarefa: Tarefa[]
}

const TarefaExample: React.FC<TarefaProps> = () => {
  const [data, setData] = useState<Tarefa[]>()

  useEffect(() => {
    setData(Data)
  }, [])

  return (
    <>
      {data?.map((n) => {
        return (
          //Renderize sua tela
        )
      })}
    </>
  )
}

Remember the typescript studies that you have to make the statements and point out in your component/class which interface it should follow.

  • Use state to set the initial state of the application.
  • Use useEffect to change your data before the application starts.

If necessary, add a loading to your application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.