My component successfully fetches info (texts and images) from the Django backend but fails to display the images.
related: react.js doesn't display fetched image
I removed file 192png from manifest.js and HTML and it didn't work so I put them back again as advised.
import React, { useState, useEffect, Fragment} from 'react';
import axios from 'axios';
import Carousel from 'react-elastic-carousel';
import './Schools.css';
import Test from '../assets/images/back.jpg';
const schoolBreakPoints = [
{width: 1, itemsToShow: 1 },
{width: 550, itemsToShow: 2 },
{width: 768, itemsToShow: 3 },
{width: 1200, itemsToShow: 4 },
];
function Schools() {
const [languageCenters, setLanguageCenters] = useState ([]);
useEffect(() => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const getLanguageCenters = async () => {
try {
const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/partners/list/`, config);
setLanguageCenters(res.data);
}
catch (err) {
}
};
getLanguageCenters();
}, []);
const getAllLanguageCenters = () => {
let allLanguageCenters = [];
let results = [];
languageCenters.map(languageCenter => {
console.log(languageCenter.photo)
return allLanguageCenters.push(
<Fragment key={languageCenter.id}>
<div className='school__display'>
<img className='school__display__image' src={languageCenter.photo} alt='school logo' />
</div>
<h3 className='school__language__center'>{languageCenter.name}</h3>
<p className='school__course'>{languageCenter.country}</p>
<p className='school__course'>{languageCenter.language}</p>
<p className='school__course'>{languageCenter.course}</p>
<p className='school__about'>{languageCenter.note}</p>
</Fragment>
);
});
for (let i = 0; i < languageCenters.length; i += 20) {
results.push(
<div key={i} className='school__card__row'>
<Carousel breakPoints={schoolBreakPoints}>
<div className='school__card'>
{allLanguageCenters[i]}
</div>
<div className='school__card'>
{allLanguageCenters[i+1] ? allLanguageCenters[i+1] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+2] ? allLanguageCenters[i+2] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+3] ? allLanguageCenters[i+3] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+4] ? allLanguageCenters[i+4] : null}
</div>
</Carousel>
</div>
);
}
return results;
};
return (
<div className='schools'>
<section className='schools__language__centers'>
<div className='schools__row'>
<h2 className='schools__subheading'>Language Centers</h2>
</div>
{getAllLanguageCenters()}
</section>
</div>
)
}
export default Schools
developer tool > all ;
developer tool > img ;
And below is what I see on the browser, only the broken icon and the rel ;
I managed to find a walk-around, when I use the build folder in Django through Django-server, the images are appearing perfectly. It's ok for me because I'm building a Django project but it's annoying why React can't display them.
Related
This question already has an answer here:
How to add new pages without rebuilding an app with +150k static pages?
(1 answer)
Closed 11 months ago.
I've jus started working and learning Next so I have a lot of confusions,
I was using the useEffect on react and it always updated the UI with the new stuff that was added to the API however, its not working on next.js
SO I have an index file
import Link from "next/link";
import react, {useState, useEffect} from "react";
import { useRouter } from 'next/router';
export async function getStaticProps({ res }) {
try {
const result = await fetch(`https://api.pandascore.co/matches/running??sort=&page=1&per_page=10&&token=#`);
const data = await result.json();
return {
props: { game: data },
revalidate: 10 // 10 seconds
};
} catch (error) {
res.statusCode = 404;
return { props: {} };
}
}
const upcomingGames = ({ game }) => {
return (
<div className="container">
<h2>Live Games - </h2>
<div className="columns is-multiline">
{game.map(q => (
<div className="column is-half" key={q.id}>
<div className="inner">
<div className="inner__box">
<Link href = {'/live/' + q.slug} key={q.slug}>
<a className="h2link" key={q.slug}> {q.name}</a>
</Link></div>
</div>
</div>
))}
</div>
</div>
);
}
export default upcomingGames;
This file is connected to a [slug].js file which displays more details about a game,
Now in production when I deployed the app to vercel I have noticed that when a new game is added to the API it displays in the index.js but when I click on it I'm redirected to a fallback(404) page.
After I redeploy my project this is fixed, however every time a new game is added and rendered I'm unable to access its individual page which I defined in [slug].js
export const getStaticPaths = async () => {
const res = await fetch(`https://api.pandascore.co/matches/running?sort=&page=1&per_page=50&token=#`);
const data = await res.json();
const paths = data.map(o => {
return {
params: { slug: o.slug.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const slug = context.params.slug;
const res = await fetch(`https://api.pandascore.co/matches/running?search[slug]=${slug}&token=#`);
const data = await res.json();
console.log(data)
return {
props: {
game: data
}
}
}
export default function live({ game }) {
return (
<div className="container">
<h2> Single Game deets.</h2>
{game.map((g) => (
<div className="container" key={g.id} >
<div className="inner-box" key={g.slug}>
{/** Fetch team and display their corresponding score - A bit of code repition :( */}
<div className="score-board-min columns is-mobile is-multiline">
<div className="column is-full"> {g.opponents.slice(0, -1).map((o) => <span className="team" key={o.id}>{o.opponent.name}</span>)}
{g.results.slice(0, -1).map((res, i) => (
<span className="scores" key={i}>{res.score}</span>
))}</div>
<div className="column">
{g.opponents.slice(-1).map((o) => <span className="team" key={o.id}>{o.opponent.name}</span>)}
{g.results.slice(-1).map((res, i) => (
<span className="scores" key={i}><div>{res.score}</div></span>
))}
</div>
</div>
<br />
<div className="lower-box columns is-multine">
<div className="column is-half">
<div className="dark"><span className="is-pulled-left">League</span> <span className="is-pulled-right">{g.league && g.league.name}</span></div>
<div className="dark"><span className="is-pulled-left">Game:</span> <span className="is-pulled-right"> {g.videogame && g.videogame.name} </span></div>
<div className="dark alt"><span className="is-pulled-left">Tournament</span> <span className="is-pulled-right"> {g.tournament && g.tournament.name} | </span></div>
<div className="dark"><span className="is-pulled-left">Series</span> <span className="is-pulled-right"> {g.serie.full_name} | {g.serie.tier.toUpperCase()} </span></div>
<div className="dark alt"><span className="is-pulled-left">Teams</span> <span className="is-pulled-right"> {g.opponents.map((o) => o.opponent.name).join(" vs ")} </span></div>
</div>
</div>
<br />
</div>
</div>
))}
</div>
)
}
During development (next dev) getStaticPaths gets called on every request, but for production it only gets called the next time you run next build. So when a new game is added to the API, the paths named after ${some_new_game_slug} won't exist until you run next build again, i.e., re-deploy. If this type of data changes frequently, you might have to use getServerSideProps for [slug].js as well (so no static paths) or opt for the client-side data fetching approach.
import { Blogs } from "../../components/Data"
import Image from "next/image";
import Link from "next/link";
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
export default function index({ posts }) {
// const Short_Blog = Blogs.map(item =>
// <div className="BLOGS_Projects" key={item}>
// <div className="BLOGS_Projects_Image">
// <Image
// className='BLOGS_Projects_image'
// src={item['img-1']}
// 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={'/blogs/' + Blogs.indexOf(item)}>
// <a>{item['title']}</a>
// </Link>
// <p>{item['desc']}</p>
// </div>
// );
return (
<div className="BLOGS_Container">
<div className="BLOGS_Sub_Container">
<div className="BLOGS_New">
<h1 style={{ marginLeft: 25 + 'px' }}>Cyber-Security Blogs</h1>
<div className="BLOGS_Present">
{posts.map( post =>{
<h1 style={{zIndex: '10000'}}>{post}</h1>
})}
</div>
</div>
</div>
</div>
)
}
export async function getStaticProps() {
const files = fs.readdirSync(path.join('posts'))
const posts = files.map((filename) => {
const slug = filename.replace('.md', '')
const markdownWithMeta = fs.readFileSync(path.join('posts', filename), 'utf-8')
const { data: frontmatter } = matter(markdownWithMeta)
return {
slug,
frontmatter
}
})
return {
props: {
posts,
},
}
}
The posts object does exist but when I try to use it in the HTML, it doesn't show up anyone got any idea why this is happening?
the posts.map that I used is not giving any errors but it also doesn't show any h1 html in actual page, the actual page seems blank.
You need to return the element to render inside the callback of map function.
1st way
{posts.map((post) => {
return <h1 style={{ zIndex: "10000" }}>{post}</h1>;
})}
2nd way
{posts.map((post) => (
<h1 style={{ zIndex: "10000" }}>{post}</h1>
))}
React will not render plain html content as a string. You need to use the dangerouslySetInnerHTML prop, like so:
{
posts.map((post) => {
return <div dangerouslySetInnerHTML={{__html: post}}></div>
})
}
You can read more about it here:
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
Alternatively you can use something like next-mdx-remote, which you can learn about here:
https://github.com/hashicorp/next-mdx-remote
I am building out a row of react-icons. When selected the icons to display content from a static .JSON file. I am trying to combine the following events:
Change color when clicked
Change/Switch between the static .JSON content when clicked.
I tried to combine the 2 actions inline based on this post.
However, only the color changes, not the .JSON data.
Thank you in advance, any help or guidance would be appreciated.
Here is my code below:
import React, { useState } from "react";
import "../Styles/arrow.css";
import { BsFillPeopleFill } from "react-icons/bs";
import { GiLinkedRings } from "react-icons/gi";
import { GoArrowRight } from "react-icons/go";
function Icon(props) {
const handleClick = (messageKey) => () => props.setSelectedIcon(messageKey);
const [bg, changeBGColor] = React.useState(1);
return (
<div className="icon-arrow">
<div className="arrow">
<div className="arrow-line" />
<div className="arrow-icon">
<GoArrowRight />
</div>
</div>
<div className="icons">
<GiLinkedRings
className="rings"
onClick={() => {
handleClick("rings");
changeBGColor(1);
}}
style={{
backgroundColor: bg === 1 ? "#e3e1dc" : "#ae7a67",
}}
/>
<BsFillPeopleFill
className="family"
onClick={() => {
handleClick("family");
changeBGColor(2);
}}
style={{
backgroundColor: bg === 2 ? "#e3e1dc" : "#ae7a67",
}}
/>
</div>
</div>
);
}
export default Icon;
My .JSON Data: iconmessage.json
{
"rings": {
"image": "rings.jpg",
"title" : "Rings",
"message":"Lorem Ipsum"
},
"family": {
"image": "family.jpg",
"title" : "Family is essential",
"message":"Lorem Ipsum"
}
}
Icons/.JSON being pulled from IconMessage.JSX
import React from "react";
import "../Styles/iconmessage.css";
import messages from "../Static/iconmessage.json";
function IconMessage(props) {
const message = messages[props.selectedIcon]
return (
<div className="icon-message">
<div className="title-message">
<div className="title">{message.title}</div>
<div className="message">{message.message}</div>
</div>
<div className="image">
<img src={`/images/${message.image}`} alt="" srcset="" />
</div>
</div>
)
}
export default IconMessage
What you did what correct from the onClick perspective. I'd say that the problem is the value you pass. Are you sure that when you pass "rings" to selectedIcon, it should render the JSON as you'd wish?
I think the problem is that you access messages.title, messages.message, instead of messages.image.title, messages.image.message.
I have two components,
Uploader Component
Which uploads the file to Azure storage
ContainerList Component
Which fetches the uploaded file's data from Azure storage.
For fetching data from azure and show in ContainerList, I referred to ListBlobs in (https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html)
My components are completely independent components that were imported in a different react project by using npm-link. For npm link, I referred to this documentation (https://60devs.com/simple-way-to-manage-local-node-module-using-npm-link.html)
import {Uploader, ContainerList} from 'blobuploader';
import React from 'react';
class App extends React.Component{
render(){
return (
<Uploader
accountName={azureCredentials.accountName}
sasToken={azureCredentials.sasToken}
multiple={true}/>
<ContainerList
accountName={azureCredentials.accountName}
sasToken={azureCredentials.sasToken} />
);
}
}
The main issue is when I uploaded files to Azure storage by using the Uploader Component. Container List is not updating i.e the newly uploaded file to azure storage is not reflected in ContainerList. Need to reload the page for seeing updated data in ContainerList.
For example, you can see below the image where a new file has been uploaded but not showing in the list(i.e ContainerList)
Please help me to resolve this issue.
Thanks in advance
ContainerList code
import React from 'react';
import '../css/containerList.css';
import axios from 'axios';
import PROGRESS from '../assets/progress.svg'
import PropTypes from 'prop-types';
class ContainerList extends React.Component{
constructor(props){
super(props);
this.state= {
datas: [],
};
this.blobService = null;
this.initConnections.bind(this);
}
componentDidMount(){
const script = document.createElement('script');
script.src = "https://dmrelease.blob.core.windows.net/azurestoragejssample/bundle/azure-storage.blob.js";
script.async = true;
document.body.appendChild(script);
script.onload = () => {
this.initConnections();
};
console.log('script ended');
}
initConnections = () => {
var accountName = this.props.accountName;
var SasToken = this.props.sasToken;
var blobUri = 'https://' + accountName + '.blob.core.windows.net';
this.blobService = this.blobService === null ? AzureStorage.Blob.createBlobServiceWithSas(blobUri, SasToken) : this.blobService;
this.blobService.getServiceProperties({options: ['clientRequestId']}, (error, result)=>{
if(error){
console.log('Error Creating Blob Service..')
console.log(error);
} else {
this.blobService.listBlobsSegmented('my-con', null, {include:["metadata"]}, (error, results) => {
if (error) {
console.log(error);
}
else {
var temp =[]
results.entries.map(async (ele,index) => {
console.log('Tag',ele);
var val = index+1;
var type = ele.contentSettings.contentType;
temp.push({number:val,name:ele.name,type,status:<button className='container-button'>PASS</button>,email:"testtagcheck123456#gmail.com",apiStatus:PROGRESS});
if(results.entries.length === temp.length){
this.setState({datas:temp});
}
});
}
});
}
});
}
render(){
//SHOWING DATA IN UI LIST FROM this.state.datas
return (
<div className= "table-box">
<div className="table-row-head">
{
(["No","File-Name","Type","Status","Outlook-Mail","API-Status"]).map((ele => {
return( ele === "No" ?<div className="table-cell table-head first-cell" style={{width:'4%'}}>
<p className ="heading-label">{ ele} </p>
</div> : <div className="table-cell table-head" style={{width:'20%'}}>
<p className="heading-label">{ ele} </p>
</div>)
}))
}
</div>
{
this.state.datas.map( (eles,index) => {
return (
<div className='table-row' key={index}>
<div className="table-cell first-cell" style={{width:'4%'}}>
<p>{ eles.number} </p>
</div>
<div className="table-cell" style={{width:'23%'}} >
<p>{eles.name} </p>
</div>
<div className="table-cell" style={{width:'20%'}} >
<p >{eles.type} </p>
</div>
<div className="table-cell" style={{width:'15%'}} >
<p>{eles.status} </p>
</div>
<div className="table-cell" style={{width:'23%'}}>
<p>{eles.email} </p>
</div>
<div className="table-cell" style={{width:'15%'}}>
<img src={eles.apiStatus} alt="PROGRESS" style={{width:'30%',}}/>
</div>
</div>
);
}
)
}
</div>
);
}
}
ContainerList.propTypes = {
accountName: PropTypes.string,
sasToken: PropTypes.string,
}
export default ContainerList;
As being designer and novice to react, I developed code in which local array is displaying as image and json data as title. Titles are working fine but images are not displaying and showing all of arrays in src attribute.
I have used Axios.get() to fetch data from the server.
I am missing out in logic somewhere while developing map inside map. I would be grateful for getting help.
EDIT : I want one image with one title.
CommonMeds.js
import React, { Component } from 'react';
import './CommonMeds.scss';
import MedSection from '../../Components/MedSection/MedSection';
import Axios from 'axios';
class CommonMeds extends Component {
state = {
MedTitle: [],
TitleImg: [
{ imageSrc: require('../../../../images/medstype_1.svg') },
{ imageSrc: require('../../../../images/medstype_2.svg') },
{ imageSrc: require('../../../../images/medstype_3.svg') },
{ imageSrc: require('../../../../images/medstype_4.svg') },
{ imageSrc: require('../../../../images/medstype_5.svg') },
{ imageSrc: require('../../../../images/medstype_6.svg') },
{ imageSrc: require('../../../../images/medstype_7.svg') },
{ imageSrc: require('../../../../images/medstype_8.svg') },
{ imageSrc: require('../../../../images/medstype_9.svg') },
{ imageSrc: require('../../../../images/medstype_10.svg') },
]
};
componentDidMount() {
const medInfo = Axios.get('URL OF JSON DATA');
medInfo.then( response => {
this.setState({MedTitle: response.data.result});
});
}
render() {
const Meds = this.state.MedTitle.map(med => {
const imglable = this.state.TitleImg.map(src => {
return src.imageSrc;
})
return <MedSection
Title={med.medicationCategory}
src = {imglable}
/>;
});
return(
<div className="container">
<h3 className="text-left">Common Medicines with Categories</h3>
<hr />
{Meds}
</div>
);
}
}
export default CommonMeds;
MedSection.js
import React from 'react';
import './MedSection.scss';
import MedicineList from '../MedicineList/MedicineList';
const MedSection = (props) => {
return (
<div className="col-12">
<div className="row">
<div className="col-12 col-md-3 col-lg-2 px-0">
<div className="c-medsimg-box py-4 px-2">
<img src={props.src} alt="Medication Type Icon" className="img-fluid" />
<h5 className="mt-3" key={props.key}>{props.Title}</h5>
</div>
</div>
<div className="col-12 col-md-9 col-lg-10">
<div className="h-100 d-flex align-items-center">
<ul className="c-medslist-ul pl-0 mb-0">
<MedicineList />
</ul>
</div>
</div>
</div>
<hr />
</div>
)
}
export default MedSection;
You are currently creating an array of images for each MedTitle. You could instead take the entry from TitleImage that has the same index as the current med in your loop instead.
You can also make it safe by using the % operator, so that if your MedTitle array is larger than your TitleImage array, you will still get an image.
const Meds = this.state.MedTitle.map((med, index) => {
const src = this.state.TitleImg[index % this.state.TitleImg.length].imageSrc;
return <MedSection Title={med.medicationCategory} src={src} />;
});
As long as length of both arrays are same, it will work.
Try using this.
const imglable = this.state.TitleImg.map(src => {
return src.imageSrc;
})
const Meds = this.state.MedTitle.map((med, index) => {
return <MedSection
Title={med.medicationCategory}
src = {imglable[index]}
/>;
});