1
votes

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?

2
import { booksData } from "path/to/file.js"Phil
What exactly do you mean by "dynamically"? Do you expect the data in this .js file to change? If so, when and how does it change? If not, you can simply bundle it by importing it as abovePhil

2 Answers

1
votes
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>
         )})}
    </>
)}
-2
votes

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