Image doesn't show up in react render - html

I want to add an image in a tinder-clone app. I followed the mern stack tutorial on the clever programmer youtube channel. Unfortunately, the image didn't show up in the browser.
This is my code:
import React, { useState } from 'react';
import "./TinderCards.css";
import TinderCard from 'react-tinder-card';
function TinderCards() {
const [people, setPeople] = useState([
{
name: 'Elon Musk',
url: "https://upload.wikimedia.org/wikipedia/commons/3/34/Elon_Musk_Royal_Society_%28crop2%29.jpg",
},
]);
const swiped =(direction, nameToDelete) => {
console.log("removing: " + nameToDelete);
};
const outOfFrame = (name) => {
console.log(name + "left the screen!");
};
return (
<div className="tinderCards">
<div className="tinderCards__cardContainer">
{people.map(person => (
<TinderCard
className="swipe"
key={person.name}
preventSwipe= {["up", "down"]}
onSwipe={(dir) => swiped(dir, person.name)}
onCardLeftScreen={() => outOfFrame(person.name)}
>
<div
style={{ backgroundImage: 'url(${person.url})' }}
className="card"
>
<h3>{person.name}</h3>
</div>
</TinderCard>
))}
</div>
</div>
);
}
export default TinderCards
And this is what I see in the browser:
tinder clone

Related

Data passing probelm between files in next js

So i have three files here :-
project.js
import Image from 'next/image';
import Link from 'next/link'
import { DATA } from '../../components/Data'
const WEB_RELATED = []
const PC_EXES = []
for(let i=0;i<DATA.length; i++){
if(DATA[i]['loc'] == 'WEB'){
WEB_RELATED.push(DATA[i])
}
else if(DATA[i]['loc'] == 'EXE'){
PC_EXES.push(DATA[i])
}
}
const WEB = WEB_RELATED.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
<Link href={'/projects/' + WEB_RELATED.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
const PC = PC_EXES.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
<Link href={'/projects/' + PC_EXES.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
export default function index() {
return (
<div className="PROJECTS_Container">
<div className="PROJECTS_Sub_Container">
<div className="PROJECTS_New">
<h1>Web-Related</h1>
<div className="PROJECTS_Present">
{WEB}
</div>
</div>
<div className="PROJECTS_New">
<h1>Pc apllications</h1>
<div className="PROJECTS_Present">
{PC}
</div>
</div>
</div>
</div>
)
}
Project Display page [project.js]
import { useRouter } from 'next/router'
import { useState } from 'react';
import Image from 'next/image';
import { DATA } from '../../components/Data';
import React, {useEffect} from 'react';
export default function title() {
const router = useRouter();
const { project } = router.query
const [state, setState] = useState()
// when user comes here i want the item sent to be read and injected into the html
useEffect(() => {
// project && console.log('value', project, 'length : ', project.length);
// setState(project)
console.log(DATA[project]['loc'])
}, [router])
return (
<div className='DISPLAY_Container'>
<div className="DISPLAY_Sub_Container">
<div className="DISPLAY_Image">
<Image
src={'/img/Projects/Cluq.PNG'}
layout='fill'
/>
</div>
<div className="DISPLAY_Info">
<h3>{state}</h3>
SUS
<p>lorem300</p>
</div>
</div>
</div>
)
}
DATA.JS file where i've kept all of the objects i want to be shown
export const DATA = [
{
'loc':'WEB',
'title':"Bukkit List",
'img':'/img/Projects/Bukkit-List.PNG',
'desc':"Bukkit-List is a easy to use and free task managing webapp, with password protection now!",
'fullDesc':""
},
{
'loc':'WEB',
'title':"SilenxIka-Github",
'img':'/img/Projects/SilenxIkaGithub.PNG',
'desc':"First github website for Project SilenxIka, which is completly made from vanilla HTML/CSS/JS",
'fullDesc':""
}
]
when someone presses a link in the first file (check there are coments above the link) the item in the link shall be passed to the second file and i can use the item in [project].js file to inject it into the html
You can append query parameters to your url and use the useRouter hook from "next/router" for getting the content of those query parameters in your other file.
Let's imagine your item object has an id and we want to append that id as a query parameter to your route:
In project.js:
export const arrayOfItems = [
{id: 'A', title: 'A title'},
{id: 'B', title: 'B title'},
{id: 'C', title: 'C title'},
{id: 'D', title: 'D title'},
];
// Add query param "item_id" plus the id of your item to your url (note the '?')
{arrayOfItems.map((item)=>
<Link href={'/projects?item_id= + item.id }>
<a>{item.title}</a>
</Link>
)
In your product display page:
import { useRouter } from "next/router";
import { arrayOfItems } from "./project.js"; // path to where array is exported from
const ProductPage = () => {
const router = useRouter();
useEffect(() => {
// here you have access to the query parameters
console.log(router.query?.item_id);
// get item_id from route
const routeItemId = router.query?.item_id;
// search through array and find item with matching id
const matchingItem = arrayOfItems.find((item)=> item.id === routeItemId && item);
console.log(matchedItem);
}, [router]);
return(<></>)
}

How can i redirect to full post after click on title

I did data display from json with titles from all posts and now i need to do redirect to page with title and body after click on title, any ideas? Thanks for help
import "./style.css";
class Card extends React.Component {
state = {
loading: true,
posts: [],
};
async componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const posts = await response.json();
this.setState({ posts, loading: false });
}
render() {
return (
<div>
{this.state.loading || !this.state.posts.length === 0 ? (
<div> loading...</div>
) : (
<div>
{this.state.posts.map((post) => (
<div key={post.id} className="post-header">
{post.title}
</div>
))}
</div>
)}
</div>
);
}
}
export default Card;```
I would recommend you to use Functional component as it would make your code short and much more readable.
But as per your code you can simply get the desired results by the making the following changes in your code.
import { useHistory } from 'react-router-dom';
class Card extends React.Component {
const history = useHistory();
render() {
return (
<div>
{this.state.loading || !this.state.posts.length === 0 ? (
<div> loading...</div>
) : (
<div>
{this.state.posts.map((post) => (
<div key={post.id} className="post-header">
<div onClick={() => history.push(post.title)}>
{post.title}
</div>
</div>
))}
</div>
)}
</div>
);
}
}
import "./style.css";
class Card extends React.Component {
state = {
loading: true,
posts: [],
};
async componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const posts = await response.json();
this.setState({ posts, loading: false });
}
gotoPage=(data)=>()=>{ //write this function above render
this.props.history.push('/'+data);
}
render() {
return (
<div>
{this.state.loading || !this.state.posts.length === 0 ? (
<div> loading...</div>
) : (
<div>
{this.state.posts.map((post) => (
<div key={post.id} className="post-header">
<span onClick={this.gotoPage(post.title)}>{post.title}</span> // You can use this function, when user user click on title, navigate page to that title
</div>
))}
</div>
)}
</div>
);
}
}
export default Card;```

Child component does not render properly

In my code, the parent component is Bucket.js and the child component is the ListItem.js. The parent component makes a call to the db and gets back an object that has a structure of: [{...},{...},{...}], which will be stored into this.state.search.
When I render each child component, only the first <div> tag in <ListItem> displays. Everything after that does not render, I cannot figure out why that is the case.
Bucket.js
import React, { Component, useState } from "react";
import axios from "axios";
import ListItem from "./ListItem";
class Bucket extends Component {
constructor() {
super();
this.state = {
search: [],
};
}
componentDidMount() {
axios
.get(`http://localhost:9000/viewCribb`)
.then((response) => response)
.then((result) => {
this.setState({ search: result.data });
console.log("Search State: ", this.state);
});
}
render() {
{
console.log("Rendering!");
}
return (
<>
{this.state.search ? (
<>
{Object.keys(this.state.search).map((item, index) => (
<ListItem
{...this.props}
key={this.state.search[item].address_id}
listing={this.state.search[item]}
></ListItem>
))}
</>
) : (
<></>
)}
</>
);
}
}
export default Bucket;
ListItem.js
import React from "react";
import classNames from "classnames";
const ListItem = (...props) => {
console.log("props", props);
return (
<>
<div>{props[0].listing.streetaddress}</div>
<div className="tiles-item reveal-from-right" data-reveal-delay="200">
<div className="tiles-item-inner">
<div className="testimonial-item-content">
<p className="text-sm mb-0">{props[0].listing.streetaddress}</p>
</div>
<div className="testimonial-item-footer text-xs mt-32 mb-0 has-top-divider">
<span className="testimonial-item-name text-color-high">
Roman Level
</span>
<span className="text-color-low"> / </span>
<span className="testimonial-item-link">
<div href="#0">AppName</div>
</span>
</div>
</div>
</div>
</>
);
};
export default ListItem;
According to:
https://www.npmjs.com/package/react-axios
https://github.com/axios/axios
this might be wrong:
componentDidMount() {
axios
.get(`http://localhost:9000/viewCribb`)
.then((response) => response)
.then((result) => {
this.setState({ search: result.data });
console.log("Search State: ", this.state);
});
}
the existence of two .then to get the response feels wrong.
It seems you are following the pattern mentioned at:
https://www.digitalocean.com/community/tutorials/react-rendering-arrays-in-react
It might be a good idea if you could share the data returned through the response and compare its structure to see it it fits your needs
The problem had to do with my css, it did not get imported properly

Understanding React.JS JSON feed and how to parse

I've got the following code which is looping through an JSON file from an API and loops through some posts.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//https://alligator.io/react/axios-react/
import axios from 'axios';
export default class PostList extends React.Component {
state = {
posts: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
Pulls in post slugs from Domain
</p>
<ul>
{ this.state.posts.map(post => <li>{post.name} - {post.username} </li>)}
</ul>
</div>
)
}
}
This works fine, and gets the information which was needed.
Now, in my test JSON file, the format is as follows:
https://jsonplaceholder.typicode.com/users
But in my actual JSON file from WordPress Rest API, we have another item, named core_layout:
JSON image
My issue is, trying to use the same code such as {post.name}does not get the information needed such as core_layout->image->name.
Is there an easy way around this?
Thanks all!
EDIT:
Tried the answers below, but still no luck, get the error TypeError: Cannot read property 'map' of undefined:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//https://alligator.io/react/axios-react/
import axios from 'axios';
export default class PostList extends React.Component {
state = {
posts: [],
coreLayout: {}
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
// const posts = res.data;
//this.setState({ posts });
const { posts, core_layout: coreLayout } = res.data;
this.setState({ posts, coreLayout });
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
Pulls in post slugs from domain
</p>
<ul>
{ this.state.posts.map(post => <li>{post.name} - {post.core_layout.image.name}</li>)}
</ul>
</div>
)
}
}
EDIT 2:
Tried the below: This gets the title, but again, not the actual corelayout I need.
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
movies: []
}
}
componentDidMount() {
let dataURL = "http://zinsseruk.com/wp-json/wp/v2/posts?per_page=1";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
movies: res
})
})
}
render() {
let movies = this.state.movies.map((movie, index) => {
return <div key={index}>
<p><strong>Title:</strong> {movie.title.rendered}</p>
<p><strong>Title:</strong> {movie.core_layout.acf_fc_layout}</p>
</div>
});
return (
<div>
<h2>Star Wars Movies</h2>
{movies}
</div>
)
}
}
export default App;
Replace const posts = res.data; with const posts = res.data.core_layout;. Then you'll get an array similar to what you have in your test file.
I think you need to understand the JSON structure you receive from the API. Where is located core_layout property? Inside each post property as a children?
So in the posts loop you can use post.core_layout.image.name for image name, for example (and so on with other properties).
If core_property is at the root of the data you receive, you can load it inside your state like so:
state = {
posts: [],
coreLayout: {}
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
// This is equivalent of doing
// const posts = res.data.posts
// const coreLayout = res.data.core_layout
const { posts, core_layout: coreLayout } = res.data;
this.setState({ posts, coreLayout });
})
}
Then use it in your code by using local component state:
render() {
...
// For example image name:
console.log('image name', this.state.coreLayout.image.name)
...
}

Accessing certain item after fetching data from API with react

I am learning react and stumbled on something that seems like an absolute beginner problem. Anyway I am fetching data from an API and would like to know how to get a certain element from the JSON. I have tried different variations with [] but with no success.
JSON:
[{"name":"gfhf","id":1,"organizer":"hfgh"},{"name":"World Cup","id":2,"organizer":"FIFA"}]
React code:
import React, { Component } from "react";
import Tournaments from "./Tournaments";
const tournyAPI = 'http://localhost:8080/api/tournaments';
class template extends Component {
constructor() {
super();
this.state = {
data: [],
}
}
componentDidMount() {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
console.log(findresponse)
this.setState({
data:findresponse,
})
})
}
render() {
return (
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron text-center">
{
this.state.data.map((dynamicData, key) =>
<div>
<h1>{dynamicData.name}</h1>
</div>
)
}
</div>
</div>
</div>
</div>
);
}
}
export default template;
My goal would be to display only World cup for example.
You can filter out whatever you want from the response from the API. Like below:
Notice the line findresponse.filter(res => res.name === "World Cup");
componentDidMount() {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
console.log(findresponse)
findresponse.filter(res => res.name === "World Cup");
this.setState({
data:findresponse,
})
})
}