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?
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>
)})}
</>
)}
// First of All You Need to import your .js file like that
import booksData from '/path/to/file.js'
Related
I'm trying to display couple of images from array of objects containing images urls. I'm aware that StaticImage has to accept local variables as props values. These two variables for image urls are both local.
Why is this not working and is there a workaround?
import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';
const TestPage = (props) => {
const itemData = [
{
img: 'https://images.unsplash.com/photo-1549388604-817d15aa0110?w=161&fit=crop',
title: 'Bed',
},
{
img: 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3?w=161&fit=crop',
title: 'Kitchen',
},
];
const testSrc = 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6?w=161&fit=crop';
const testSrc2 = itemData[0].img;
return (
<>
<StaticImage src={testSrc} alt="works" />
<StaticImage src={testSrc2} alt="doesn't" />
</>
)
}
export default TestPage;
As you said, there's a restriction in the component:
Restrictions on using StaticImage
The images are loaded and processed at build time, so there are
restrictions on how you pass props to the component. The values need
to be statically-analyzed at build time, which means you can’t pass
them as props from outside the component, or use the results of
function calls, for example. You can either use static values, or
variables within the component’s local scope. See the following
examples:
In your case, a plain assignation works but an object assignation doesn't. Change it to:
import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';
const TestPage = (props) => {
const testSrc = 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6?w=161&fit=crop';
const testSrc2 = 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3?w=161&fit=crop';
return (
<>
<StaticImage src={testSrc} alt="Bed" />
<StaticImage src={testSrc2} alt="Kitchen" />
</>
)
}
export default TestPage;
I'm learning React JS.Trying to map components by calling data from external JS file.
There is no error or issue in the code.
This is content.jsx inside the /src/component folder.Here I'm rendering mapped components from App.jsx.
import React from 'react';
export default function Content(props) {
<div>
<p> {props.name} </p>
<p> {props.rollNo} </p>
</div>
}
This is App.jsx inside the src folder
import React from 'react';
import Content from './component/content';
import Data from './Data'
export default function App() {
const jokeElements = Data.map( (ele) => {
return(
<Content name={ele.name} rollNo={ele.rollNo} />
);
})
return(
<div>
{jokeElements}
</div>
)
}
and rendering App.js to index.js which is in src folder. The data.js contains data in src folder.
Data.js file:
const Data=[
{
name:"Deepak",
rollNo:"123"
},
{
name:"Yash",
rollNo:"124"
},
{
name:"Raj",
rollNo:"125"
},{
name:"Rohan",
rollNo:"126"
},
{
name:"Puneet",
rollNo:"127"
},
{
name:"Vivek",
rollNo:"128"
},
{
name:"Aman",
rollNo:"129"
},
]
export default Data;
The issue I can output other JSX elements, but I'm not able to display mapped components. What's wrong with my code ?
Im guessing that "Content" component is the "Joke" component, if so, it has no return statement, try:
export default function Joke(props) {
return (
<div>
<p> {props.name} </p>
<p> {props.rollNo} </p>
</div>
);
}
You need a return statement in Joke function of content.js
I am trying to create a global variable that all components are rendered with by default and set that default value but I'm not sure how to do the 2nd part. Here's what I have so far in my _app.tsx:
import { AppProps } from "next/app";
import type { NextComponentType } from 'next'
import Blue from "../components/blue";
type CProps = AppProps & {
Component: NextComponentType & {model?: string }
};
const MyApp = ({
Component,
pageProps: { ...pageProps },
}: CProps) => {
return (
<>
{Component.model === 'blue' ? (
<Blue>
<Component {...pageProps} />
</Blue>
) : (
<Component {...pageProps} />
)}
</>
);
};
But this obviously doesn't give me a default value for model. It just creates that variable with null value for all the components. How do I set the value?
Side question: Is this better done using React Context?
Edit 1:
This is how the component sets the model value if it does not want to use the default value:
const ComponentFoo = () => {
return (
<>Test</>
);
};
ComponentFoo.model = 'red'
export default ComponentFoo;
This sounds like a good candidate for Next.js Layouts. You would have to compose a Layout component, similar to Blue in your example, which accepts a color prop and encapsulates the color rendering logic to the layout file. You can implement a default render path if no color prop is provided.
Then you can use it like so:
// pages/whatever.tsx
import type { ReactElement } from 'react'
import Layout from '../components/layout'
export default function Page() {
return {
/** Your content */
}
}
Page.getLayout = function getLayout(page: ReactElement) {
return (
<Layout color="blue">
{page}
</Layout>
)
}
https://nextjs.org/docs/basic-features/layouts#with-typescript
I have an Activity.js Component that I am bringing in to my App.js component that renders activities. I would like add an onlick event to a button in this component by passing a function as a prop to that button, for some reason the button isnt working, right now its a simple console.log for the logic.
The activities do display when I map through the array of objects but it seems the button isn't taking the props. Can somebody help me understand my why deleteActivity function doesn't run when I click the button?
Acitivity.js component
import React, {Component} from 'react'
export default function Activity(props) {
return (
<div>
<h1>Things I like to do </h1>
{props.activities.map((activity) => (
<div key={activity.activity} style={{ display: "flex", justifyContent: "space-between" }}>
<li >{activity.activity}</li>
<button onClick={() => props.deleteActivity}>X</button>
</div>
))}
</div>
);
}
App.js Component
import React, { Component } from 'react';
import ListContacts from './ListContacts';
import Activity from './Activity'
class App extends Component {
state = {
activities : [
{
id: 1,
activity: "pool"
},
{
id: 2,
activity: "games"
},
{
id: 3,
activity: "sports"
}
]
}
deleteActivity = ()=>{
console.log("hello")
}
render() {
return (
<div>
<Activity activities={this.state.activities} deleteActivity={this.deleteActivity} />
</div>
)
}}
export default App;
Youre passing the prop correctly, but you arent actually running the function you passsed. instead of () => { props.deleteActivity }, try adding () to the end of your function. example: () => { props.deleteActivity() }
I have the following object being exported into another file:
info.js
export const info = {
companyName: '',
title: 'Some title',
year: '',
};
I'm importing this object into my Context.js like so:
InfoContext.js
import React, { useState, createContext } from 'react';
import {info} from './info'
export const InfoContext = createContext();
export const InfoProvider = ({ children }) => {
const [state, setState] = useState({
...info,
});
return (
<InfoContext.Provider value={[state, setState]}>
{children}
</InfoContext.Provider>
);
};
What I want to do is access the object values from my state inside my App.js. - Here is what I have tried but I am not having any success:
App.js
import React from "react";
import { InfoProvider, InfoContext } from "./InfoContext";
export default function App() {
return (
<InfoProvider>
<InfoContext.Consumer>
{state => (
<>
<h1>{state.title}</h1>
</>
)}
</InfoContext.Consumer>
</InfoProvider>
);
}
I'm clearly missing something obvious here. I've tried a few things but I'm not sure what the issue is. I feel it has something to do with my object being accessed from a separate file.
Additionally, here is a sandbox link with the above code. Any help would be greatly appreciated!
Code Sandbox
You are passing your value to Provider as array, but on Consumer you expecting it to be an Object.
You need to pass an Object instead:
<InfoContext.Provider value={{state, setState}}>
Also you are using Consumer wrong. As a callback it takes whole value that you've passed in Provider, not state:
<InfoContext.Consumer>
{(value) => (
<>
<h1>{value.state.title}</h1>
</>
)}
</InfoContext.Consumer>
or using destructured assignment:
<InfoContext.Consumer>
{({state}) => (
<>
<h1>{state.title}</h1>
</>
)}
</InfoContext.Consumer>
then you can use value.setState({...}) for example. etc. But note that this is a bad practice updating state like that.
Code Sandbox