Im trying display images im fetching from API
btw url is defined
fetch(url).then((res) => {
res.blob()
.then((img) => {
console.log(img)
const objectURL = URL.createObjectURL(img);
const url = objectURL.replace(/[blob:]{5}/gi,'')
ReactDOM.render(<Gallery photos={url} />, document.getElementById('root'));
});
})
Gallery.js
import React, { Component } from 'react';
class Gallery extends Component {
constructor (props) {
super(props);
this.state = {
Images: []
}
}
componentDidMount () {
this.setState({images: this.props.photos});
}
render() {
const {image} = this.props.photos;
return (
<div >
<img
className="App"
width="300"
height="300"
src={image}
alt="dogs"/>
</div>
);
}
}
export default Gallery;
with or without the regex /[blob:]{5}/gi it is only displaying the alt prop and not the image. The image is received and the get call is successful but the objectURL url is not working. Any help?
const {image} = this.props.photos; is equivalent to
const image = this.props.photos.image;
It means, "assign the property image of this.props.photos to the variable image".
However, this.props.photos is a string. Strings don't have a image property. You simply want
const image = this.props.photos;
You are not doing anything with this.state.Images, so you can remove the constructor and componentDidMount.
/[blob:]{5}/gi doesn't do what you want it to do. It means "match all sequences of 5 characters that consist of b, l, o or :"
I.e. the character sequence bb:ol would match.
If you wanted to remove the sequence blob: at the beginning of the string, then you should be using /^blob:/i instead.
However, you shouldn't remove blob: from the URL.
Complete and simplified example
import React, { Component } from 'react';
function Gallery(props) {
return (
<div >
<img
className="App"
width="300"
height="300"
src={props.image}
alt="dogs"
/>
</div>
);
}
fetch(url)
.then(res => res.blob())
.then(img => {
ReactDOM.render(
<Gallery image={URL.createObjectURL(img)} />,
document.getElementById('root'),
);
})
Related
I am working on the following project https://github.com/codyc4321/react-udemy-course section 11 the videos app. The udemy course is found at https://www.udemy.com/course/react-redux/learn/lecture/12531374#overview.
The instructor is passing a callback down to multiple children and calling it in the lowest videoItem and the code is supposed to console log something out. I have no console log in my browser even though I've copied the code as written and double checked for spelling errors.
At the main level is App.js:
import React from 'react';
import youtube from '../apis/youtube';
import SearchBar from './SearchBar';
import VideoList from './VideoList';
class App extends React.Component {
state = {videos: [], selectedVideo: null};
onTermSubmit = async term => {
const response = await youtube.get('/search', {
params: {
q: term
}
});
// console.log(response.data.items);
this.setState({videos: response.data.items});
};
onVideoSelect = video => {
console.log('from the app', video);
}
render() {
return (
<div className="ui container">
<SearchBar onFormSubmit={this.onTermSubmit} />
<VideoList
onVideoSelect={this.onVideoSelect}
videos={this.state.videos} />
</div>
)
}
}
export default App;
videoList.js
import React from 'react';
import VideoItem from './VideoItem';
const VideoList = ({videos, onVideoSelect}) => {
const rendered_list = videos.map(video => {
return <VideoItem onVideoSelect={onVideoSelect} video={video} />
});
return <div className="ui relaxed divided list">{rendered_list}</div>;
};
export default VideoList;
the videoItem.js
import React from 'react';
import './VideoItem.css';
const VideoItem = ({video, onVideoSelect}) => {
return (
<div onClick={() => onVideoSelect(video)} className="item video-item">
<img
src={video.snippet.thumbnails.medium.url}
className="ui image"
/>
<div className="content">
<div className="header">{video.snippet.title}</div>
</div>
</div>
);
}
export default VideoItem;
The code that isn't running is
onVideoSelect = video => {
console.log('from the app', video);
}
My guess is that it has something to do with a key prop not being present in the map - I'm not super well versed with class components but I can't find anything else funky so maybe try adding a unique key prop in the map.
When rendering components through a map react needs help with assigning unique identifiers to keep track of re-renders etc for performance, that also applies to knowing which specific instance called a class method.
If you don't have a unique ID in the video prop you can use an index in a pinch, although ill advised, it can be found as the second parameter in the map function. The reason it's ill advised to use an index is if there are multiple children with the same index in the same rendering context, obviously the key parameter could be confused.
Okay-ish:
const rendered_list = videos.map((video, index) => {
return <VideoItem key={index} onVideoSelect={onVideoSelect} video={video} />});
Better:
const rendered_list = videos.map((video, index) => {
return <VideoItem key={video.id} onVideoSelect={onVideoSelect} video={video} />});
i'm learning the react techologie, i'm the first exercice i must put the images like this, but when i use the map function to put the images i don't saw the images :/
image dynamics example
import React from 'react'<br>
import './Style/App.css'
const tabImg = ['./img/html.png', './img/css.png', './img/javascript.png', './img/logo192.png']<br>
const displayImgTech = tabImg.map((tech) => <img key={tech} src={tech} alt="techno"/>)<br>
export const Header = () => {
return (
<div className='container'>
<img src={displayImgTech} alt='technoFE'/>
</div>
)
}
Thank you
By passing displayImgTechin the src img props your are not adding an url but an "array" of img tags. so you just need to call {display take in your div like this:
const displayImgTech = tabImg.map((tech) => <img key={tech} src={tech} alt="techno"/>)<br>
export const Header = () => {
return (
<div className='container'>
{displayImgTech}
</div>
)
}
Is is possible to render an input (for adding caption to images) inside the draft js and can get the data which is typed by user? I am familiar with "custom block rendering" concept and followed the instruction which is provided by https://draftjs.org/docs/advanced-topics-custom-block-render-map/ But, when I wanted to write something in the input, I faced the below error:
invariant.js:40 Uncaught Invariant Violation: Unknown DraftEntity key: null.
In fact, block?.getEntityAt(0) returns null, since character list changes when I started to type.
This is the custom block renderer code:
import React from "react";
import { fromJS } from "immutable";
export const CustomBlockRenderer = (block, editorState, props) => {
if (block.getType() === "atomic") {
return {
component: Media,
editable: false,
};
}
return null;
};
const Image = (props) => {
if (!!props.src) {
return <img src={props.src} />;
}
return null;
};
const Media = (props) => {
const entity = props.contentState?.getEntity(props?.block?.getEntityAt(0));
const { src } = entity?.getData();
const type = entity?.getType();
let customBlock;
if (type === "image") {
customBlock = (
<figure className="custom-block__image-wrap">
<Image src={src?.url} className="custom-block__image" />
<figcaption className="custom-block__caption">{src?.caption}</figcaption>
</figure>
);
} else {
return null;
}
return customBlock;
};
I faced with a similar issue recently. Here the simplified demo of how it can work. Pay attention that EditorBlock component from draft-js is used on the image caption node. You should use EditorBlock in your custom component if you want an editable area inside the custom component.
class MyCustomBlock extends React.Component {
render() {
const imgSrc = this.props.block.get("data").src;
return (
<div className="my-custom-block">
<figure className="custom-block__image-wrap">
<img src={imgSrc} className="custom-block__image" />
<figcaption className="custom-block__caption">
<EditorBlock {...this.props} />
</figcaption>
</figure>
</div>
);
}
}
I've managed to create a mockup json that i need to test a json request via axios on a react app.
For now, i can console.log the json file structure and can assign the data for the link.
The problem is that my content it's not being rendered correctly in the DOM via Map Method. the images are not appearing.
import {Link} from 'react-router-dom';
import axios from 'axios';
class DesignItem extends Component {
state = {
isLoading: true,
designs: [],
error: null
}
componentDidMount () {
axios.get('http://www.mocky.io/v2/5dadd81c2d0000e0f5e4bd57')
.then (res => {
console.log(res.data);
const designs = res.data;
this.setState({designs})
})
}
render() {
return (
<React.Fragment>
{this.state.designs.map(designs => (
// this one is appearing right as expected
<Link to={designs.productPage}>
<div className="design-item" key={designs.id}>
// this image doesn't appear. the URL is there but the image it's broken
<img src={designs.featUrl} alt="" />
</div></Link>
))}
</React.Fragment>
);
}
}
export default DesignItem;```
<React.Fragment>
{this.state.designs.map(designs => (
<Link to={designs.productPage} key={designs.id}> // I think the key must be put here instead on the div
<div className="design-item">
<img src={designs.featUrl} alt="" />
</div>
</Link>
))}
</React.Fragment>
Also upon checking the data, the image source was like this:
../images/products/alexandre-iii/0.jpg
Maybe that is why it is not showing up, if you could change the url to something like:
https://your-domain.com/public/images/products/alexandre-iii/0.jpg
It will show up.
I want to use the new feature on React v16.0.0 for returning a string, then use that string in
<img src="returnedString" >
What is the current behavior?
Well if I render my component in a
<div > <MyComponent /> </div>
I can see the string displayed on the screen (see attached screenshot), but my goal is to use that string in <img src="returnedString" />
here is my code:
// My component that returns strings
class MyComponent extends Component {
render(){
switch (this.props.type) {
case 'text':
return this.props.json.data[this.props.Key]
break
case 'image':
return this.props.json.data[this.props.Key]
break
default:
return null
break
}
}
}
const UserComponent = (props) => {
return (
<div>
{/* this displays the string on the page */}
<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />
{/* If I console.log this line I get <img src={[object object]} /> */}
<img src={<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />} />
</div>
)
}
// Parent Component
class App extends Component {
constructor(props){
super(props)
this.state = {
json:[]
}
}
// Fetching data from an api
componentDidMount(){
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then(json => {
this.setState({json: json })
})
}
render() {
return (
<div>
<UserComponent {...this.state}/>
</div>
);
}
}
export default App;
How Can I achieve that?
What is the expected behavior?
I want to use the returned string inside an
Which versions of React ?
React v16.0.0
Did this work in previous versions of React?
No because it's a new feature in React v16.0.0
If you want to set the image's src attribute dynamically, then use a plain javascript function instead of a component:
const getImageSrc = props => {
switch (props.type) {
case 'text':
case 'image':
return props.json.data[props.Key]
}
}
Then you can call it from your component's render method like this:
<img src={ getImageSrc({...this.props, type: 'image', Key: 'avatar'}) } />
Because this
<MyComponent type='image' Key='avatar' desc='Abified image' />
is creating a text node in the dom.
But in this case
<img src={<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />
your src attribute is getting a react element object.
You'll never get a string like that.
If you want to get your src dynamically, try something like this
const UserComponent = (props) => {
// calculate you src here
const imageSrc = props.json.data['avatar'];
return (
<div>
<img src={ imageSrc } />
</div>
)
}
Hope this helps.