Unable to resolve an image in an array in React JS - arrays

I'm attempting to import images into an array in React JS. My intention is to be able to map through the array and have the images appear one as a time. However, my images are not being properly resolved. I'm fairly certain it is a syntax error of my doing, but I'm just not able to solve this. I'm currently a student who is just learning react, so any and all help is much appreciated!
import universe from "./images/universespider.jpeg"
let content = [
{
title: "Universe",
image: universe,
author: "Alex",
date: "09/09/8099",
blog: "Spider-Man is in different universes.",
},
]
import "./blogs.css"
import content from "../../content"
export default function blogs() {
return (
content.map((blog, i) => (
<div key={i}>
<div className="blogBox">
{blog.title}
{blog.image}
{blog.author}
{blog.date}
{blog.blog}
</div>
</div>
)
))
}
Error Message

You can't use imported images directly, in your case you should use element and pass your image as a source.
Instead of
{blog.image}
try this
import universe from "./images/universespider.jpeg"
...
<img src={universe} alt="universe"/>
More information about this assuming that your app was created with CRA.

Related

Unable to display pokemon image from pokeapi.co

I am having an issue where I can't seem to be able to display the pokemon images on my react front end, this is the api: https://pokeapi.co/
import React, { Component } from 'react';
class Card extends Component {
state = {
name: "",
imageUrl: "",
pokemonIndex: "",
}
componentDidMount() {
const {name, url} = this.props;
const pokemonIndex = url.split('/')[url.split('/').length - 2];
const imageUrl = `http://pokeapi.co/media/sprites/pokemon/${pokemonIndex}.png`
this.setState({name, imageUrl, pokemonIndex})
}
render() {
return (
<div className="card" >
<img src= {this.state.imageUrl}/>
<h3> {this.state.name} </h3>
</div>
);
}
}
export default Card;
I have also attached a screenshot of the front end.
Looking at the documentation and JSON file from API, I think I found your problem. You are using the wrong img link. The correct format is: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png
For exemple:
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png" />
#erick-silva answer is not complete and prone to error.
The correct way to fetch an image for a specific pokemon is:
Fetch from PokeAPI the info for that pokemon, say bulbasaur. -> GET https://pokeapi.co/api/v2/pokemon/bulbasaur
Parse the returned JSON for the property .sprites, select the version we'd like to use and the variety for the sprite, say Pokemon Crystal front: .sprites.versions["generation-ii"].crystal.front_default
Use the provided link and load the image: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-ii/crystal/1.png
Using this method will ensure that you will always fetch the correct image in case the ids change or the name of the image isn't the id of the pokemon.
For pokeapi the correct URI format is as follows.
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/imageName.png
Currently pokemon images are not loaded as there are deleted from it's github repo.
You can find the real location of the images inside sprites folder in PokeAPI GitHub.
To get the image, there is a workaround,
https://unpkg.com/pokeapi-sprites#2.0.2/sprites/pokemon/other/dream-world/1.svg
here 1.svg should be replaced by the pokemon's id
You can find more info here

how do I interpolate a Link component in Next-i18next / React i18next that changes position in the text

Currently I'm using Next.js with Next-i18next for I18N, but I understand that the React/i18next implementation is basically the same.
The problem I'm having is that I need to interpolate a next Link component inside some translation text, but depending on the language (English vs German), the order of the text and the link would change.
For instance the text I'm struggling with is: 'Accept data policy' vs 'Datenschutzerklärung akzeptieren'
As of the moment I have a quick fix by creating two values in the translation JSON files for the text and the link and then swapping the position based on the current language. Obviously this is not a sustainable solution. I have tried to utilise the 'Trans' component but this is showing some unexpected behaviour where the translation only kicks in after the page is refreshed, otherwise you see the text inside the Trans component.
example:
function LinkText({ href, children}) {
return <Link to={href || ''}>{children}</Link>;
}
return (
<Trans i18nKey="sentence">
text before link
<LinkText href="/data-policy">{t("dataPolicy")}</LinkText>
text after link
</Trans>
);
and the JSON in question:
{
"sentence": "agree to our <1><0/></1>",
"dataPolicy": "data policy"
}
Here's a link to CodeSandbox I made to replicate the problem with in React: link
(P.S The implementation of i18next doesn't seem to effectively swap out the languages in Codesandbox at the moment, but I included it as the code is there for a MWE)
Thanks in advance for your help, this has been driving me insane.
You had few missing parts,
Your i18next config was lack of a way to fetch the locale files, I've added i18next-http-backend.
You should use Trans component to inject the link to the sentence.
Your locale json should look like this:
{
"sentence": "Accept <0>data policy</0>"
}
// TranslatedLink.js
import React from 'react';
import { useTranslation, Trans } from 'react-i18next';
import { Link } from 'react-router-dom';
function LinkText({ href, children }) {
return <Link to={href || ''}>{children}</Link>;
}
export default function TranslatedLink() {
const { t } = useTranslation(['common']);
return (
<div style={{ padding: 50 }}>
<Trans i18nKey="sentence" t={t} components={[<LinkText href="/data-policy" />]} />
</div>
);
}
A working example: https://codesandbox.io/s/react-i18n-interpolation-issue-forked-ck8l4

Playing a sound on keypress using React

I am not experienced in React so please excuse if this question will seem silly.
I have been trying to play a sound when a key is pressed on the keyboard.
I wanted to use the following solution:
https://www.npmjs.com/package/react-sampler/v/1.0.2
The problem is that when I try to play my sample i get an error:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
import React from 'react';
import './App.css';
import Sampler from 'react-sampler';
var samples = [{
file: "samples/sample1.wav",
key: 'h', // First sample
startAt: 0.2 // delay in sec
},{
file: 'samples/sample2.wav',
key: 'o', // Second sample
startAt: 0.05
}];
var ReactSamplerExample = () => ({
handleSampleLaunch: function(sample){
var elm = document.querySelector('[data-key='+sample.key+']');
elm.classList.add('active');
setTimeout(() => { elm.classList.remove('active')}, 150);
},
render: function() {
return (
<div>
<ul className="keys">
<li data-key="h">
<span className="key"></span><span className="sample">Sample 1</span></li>
<li data-key="o">
<span className="key"></span><span className="sample">Sample 2</span></li>
</ul>
<Sampler samples={samples} onLaunchSample={this.handleSampleLaunch} disabled={false} />
</div>
);
}
});
I checked the path to the files and they seem to be ok (all files are located in the same directory as the samples folder).
I'm not sure how to solve this. If there is a better tool or a simple audio API anyone can recommend or should switch to I would gladly take some advice.
Thanks in advance!
You are using react sampler for that. I like to use native html component with some customization for this situation.
Here my sample for you, hope i can help you with this sample:
Codesandbox Audio Play

React - onclick function is running on page load

the code in the file is simple. it is imported into another file that places it in a slider container. That all works I'm just having trouble with the onClick function running on page load instead of on click.
import React from 'react';
import M_IMAGE from 'assets/image.png';
function openImage() {
window.open(M_IMAGE);
}
export const slider = {
data: [
{
content: (
<img src={M_IMAGE} onClick="openImage" />
)
}
]
}
I have tried this.openImage.bind and many other variants I have seen online.
You are missing the curly braces around the onClick's event handler and need to assign it like below:
<img src={M_IMAGE} onClick={openImage}
UKS commented on the post with an response leading to the fix.
I had to delete the function because it existing caused it to run on load and change the code to
<img src={M_IMAGE} onClick={()=> window.open(M_IMAGE)} />

using links in react-i8next

I was learning react through online sources, and I'm unable to find the solution for my problem-
suppose I have a json file -
"test":"This is a test file, contact at {{email}}"
and currently i use it as -
const [t] = useTranslation();
<div>t('test',{{email}})<div>
suppose I want to change the colour of the email text only, how do I do that?
I researched online, and read the Transcomponent documentation, but I'm unable to understand how to implement it.
You'll have to exclude the {{email}} placeholder from the translated text.
So this would be the i18n part:
{
"test": "This is a test file, contact at"
}
And this would be the React part:
const { t } = useTranslation();
return (
<div>
{t("test")} <span style={{color: "hotpink"}}>{email}</span>
</div>
);
There are a lot of variations for what you are trying to do (e.g. using external stylesheet, CSS classes, and so on), but this would be a straight-forward approach.
You can handle that using a css file, for that you need to import it to your react component file:
import './styles.css';
For this to work you should create a style.css file on the same folder/directory of your react file, after that you should set a css rule:
style.css
a {
color: hotpink;
}

Resources