Home > Blockchain >  How can I import my objects file in react
How can I import my objects file in react

Time:05-30

I have an .js file where I have my books as bellow:

export const booksData = [
{
    id: "1",
    title: "1491",
    description: "A fantastic historical book",
    genre: 'Historical',
    image: "https://shop.radical-guide.com/wp-content/uploads/2020/06/1491-Front.jpg"
},

How can I import and display these books dynamically in my react application?

CodePudding user response:

import { booksData } from "path/to/file.js"

You don't really need to pass it as a prop. Only if you are using a component, then yes, you should, eg:

<Component books={booksData} />

Then, in the Component function you pass it as a prop.

function Component(props){
    return (
     <>
         {
           props.books.map(book => {
            return(
           <h1>{book.title}</h1>
         )})}
    </>
)}

If not, you can directly import to the component that object(not recommended)

import { booksData } from "path/to/file.js"

And simply:

function Component(){

    return (
     <>
         {
           booksData.map(book => {
            return(
           <h1>{book.title}</h1>
         )})}
    </>
)}

CodePudding user response:

// First of All You Need to import your .js file like that

import booksData from '/path/to/file.js'

Then you have need to use props method

  • Related