http://localhost:3000/[object%20Object] not found 404 - reactjs

In my react app, this is an array of filenames I get from server side
const photos = ["01-1913.JPG", "01-1913.1.jpg", "01-1913.2.jpg"]
and here is how I use it with JSX
{
photos.map(entry => {
return (
<div key={entry}>
<PhotoItem key={entry} url={`${process.env.REACT_APP_NODE_SERVER}/${entry}`} />
</div>
)
})
}
const PhotoItem = (url) => {
return (
<img
src={url}
onError={this.addDefaultSrc}
alt="photoItem"
style={{
width: "500px",
height: "600px",
border: "1px solid #123C69",
}}
></img>
);
};
```
I can not figure out why I am not getting the photo (only the dummy photo from the onError event I've used) and if it has anything to do with the Object%object error. Any help would be appreciated.

As mentioned in the comments, the PhotoItem component should look like this:
// Note that here props are named "props" instead of "url"
const PhotoItem = (props) => {
return (
<img
src={props.url}
onError={this.addDefaultSrc}
alt="photoItem"
style={{
width: "500px",
height: "600px",
border: "1px solid #123C69",
}}
></img>
);
};
Note that the first argument that a react component receives is props. So even if you name it url, the value that you are looking for url lives in url.url.
I also recommend to deconstruct your props like this:
const PhotoItem = ({url}) => {
return (
<img
src={url}
...
></img>
);
};

I faced this error on the developer console on a Next.js project right after upgrading Next from v10 to v12.
Turns out using an image as <img src={require()}/> is not working anymore, and throws this error.
Instead to fix the issue, you need to use Next's (almost) drop in replacement of Image component as;
import Image from 'next/image'
...
<Image src={require()}/>
This will fix the issue, if your Next project is throwing this error.

Related

How can I create a React functionnal component and get HTML attributes and ref in props with typescript?

I'm trying to make a Trello like, I'm using react-beautiful-dnd and started from the classical example.
This is where I render the card (I just replaced the div with Task, my component)
<Task
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{
userSelect: "none",
padding: 16,
margin: "0 0 8px 0",
minHeight: "50px",
...provided.draggableProps.style,
}}
>
{item.content}
</Task>
In my component, I want to get all div attributes passed in the code above.
So I did this :
import React from "react";
const Task: React.FC<JSX.IntrinsicElements["div"]> = (props) => {
const { children } = props;
return (
<div className="card card-green" {...props}>
<div className="card-content">
<div className="content">{children}</div>
</div>
</div>
);
};
export default Task;
It looks good, excepted for the "ref", I got a message in my console when I try to drag my card
Invariant failed: Cannot get dimension when no ref is set
And indeed my ref is always undefined.
Do you have an idea ?
I tried several examples found but no one works. I think I am missing a type somewhere

Images wont show up in Nextjs and Strapi project

Currently I'm using NextJs as my frontend and Strapi as my CMS for my web application. I've added the following data to my Citizenship collection type in Strapi:
This is my code in the NextJs side:
export default function Citizenship({ posts }) {
return (
<>
<div style={{textAlign:"center", marginTop:"20px", fontSize:"25px", color:"#0E2043", fontWeight: "500"}}>CITIZENSHIP</div>
<div class="flexbox-container" style={{margin:"70px", marginTop:"0px"}}>
{
posts &&
posts.map((post) => (
<div style={{ padding: "40px" }}>
<div class="citizen-item" key={post.id}>
<div className="container6">
<img
style={{ height: "50%", width: "100%" }}
src={post.Thumbnail.name}
/>
<div style={{textAlign:"center", color:"#E3AB50", padding:"10px", fontSize:"20px"}}>{post.Title}</div>
<div style={{textAlign:"center", color:"#000", padding:"10px", fontSize:"15px"}}>Access to {post.Countries} countries</div>
<div style={{display:"flex", justifyContent:"center", paddingTop:"20px", paddingBottom:"10px"}}>
<button class="findButton">FIND OUT MORE</button>
</div>
</div>
</div>
</div>
))}
</div>
</>
)
}
export async function getStaticProps() {
const res = await fetch('http://localhost:1337/citizenships');
const posts = await res.json();
return {
props: {posts},
}
}
In my output, everything is coming fine except for the Image where it is only showing my first image and all the others are giving a 404. How do I fix this?
Use console.log(post) and find what your post returns in your browser console . If it gives Thumbnail then use it .Or else use what it gives .
use postman for that route with populate query (at the end add "?populate=*") and u will get the complete position of the url of you image and use it .

Resize google map frame in react js

Currently using google-maps-react component in a contact form for a sales page. This code has successfully imported the map and it is viewable in the dimensions 450x350. My issue is, is that despite the image being 450x350 the frame or i guess div that the map api sits in still thinks the map is still default size so it pushes my entire site out with white space that is removed when i remove the Map API. No amount of adding styles as dimensions to anything around the map has fixed this.
What do i pass into the map in order to effect the size of the frame and not just the image itself?
import React, { Fragment } from "react";
import ContactForm from "../contactus/ContactForm";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";
const ContactUs = props => {
const style = {
maxWidth: "450px",
height: "350px",
overflowX: "hidden",
overflowY: "hidden"
};
return (
<Fragment>
<h2 className='lead text-primary text-center'>Get in touch</h2>
<div className='grid-2'>
<div>
<h4>Priority Consulting</h4>
<ul>
<li>
1234 Sherman Way <br />
Sherman Oaks, CA 90210
</li>
<li>info#priorityconsulting.com</li>
<li>1-800-324-3423</li>
</ul>
<Map google={props.google} style={style} />
</div>
<div>
{" "}
<ContactForm />
</div>
</div>
</Fragment>
);
};
export default GoogleApiWrapper({
apiKey: "MYKEY"
})(ContactUs);
I went back into my code and found an updated version, that made it to a final version of the site. Unfortunately the site is no longer live so cant verify if this is the best answer but, like I said its in my code, so it probably solves.
const style = {
maxWidth: "450px",
height: "350px",
overflowX: "hidden",
overflowY: "hidden"
};
const containerStyle = {
maxWidth: "450px",
height: "350px"
};
<Map google={props.google} style={style} containerStyle={containerStyle} />

React-testing-library not rendering computed styles from stylesheet

Basic scenario is such: I have a component which has width: 100% as defined in a stylesheet. Therefore it should retain the width of its parent component. I want to calculate the width of my component and apply it to my child component because I am rendering it via createPortal and I would like them to be the same width. This works in the browser. However, in my test, I am finding that window.getComputedStyle(component) is not returning any of the styles applied from the stylesheet.
As suggested, I could mock the javascript window, but that's actually counter to what I'm hoping to do, I think. I want to verify the behavior that is present in the browser, that window.getComputedStyle() returns all styles applied, not just the inline styles.
I have put a simple example into a codesandbox: https://codesandbox.io/s/goofy-wilson-6v4dp
Also here:
function App() {
return (
<div className="App">
<WidthComponent />
</div>
)
}
function WidthComponent() {
const myInput = useRef();
const [inputWidth, setInputWidth] = useState(0);
useEffect(() => {
console.log("in handleLoad");
const width = myInput.current ? myInput.current.offsetWidth : 0;
setInputWidth(width);
}, [myInput]);
return (
<div className="inherited-width" ref={myInput}>
<div style={{ width: inputWidth }} className="child-element">
Hello
</div>
</div>
);
}
// test
test("width is inherited", () => {
const { rerender } = render(
<div style={{ width: "452px" }}>
<WidthComponent />
</div>
);
const element = document.getElementsByClassName("child-element").item(0);
rerender(
<div style={{ width: "452px" }}>
<WidthComponent />
</div>
);
expect(window.getComputedStyle(element).width).toBe("452px");
});
.App {
font-family: sans-serif;
text-align: center;
width: 500px;
}
.inherited-width {
width: inherit;
}
Any help is appreciated.
However, in my test, I am finding that window.getComputedStyle(component) is not returning any of the styles applied from the stylesheet.
Note that if you're running your tests in JSDOM (i.e. every Jest test) then CSS isn't fully implemented. Specifically, the cascade part of CSS is not implemented (https://github.com/jsdom/jsdom/pull/2690). Inheritance is only partially implemented (display and visibility) (https://github.com/jsdom/jsdom/issues/2160).
I would suggest running tests that assert on computed styles only in browsers, not JSDOM. A codesandbox test is not running in an actual browser environment.

react-dropzone child icon not changing on state change

I have a react project and I am using the react-dropzone component:
import Dropzone from 'react-dropzone';
I want to make it stateful and show different images and text based on the state. I defined my states as:
const status = {
ready: 'ready',
preview: 'preview',
error: 'error',
requested: 'requested',
success: 'success',
failed: 'failed',
};
The state can change based on user actions (so when they drag a file onto the dropzone I update status in state as follows:
onDrop(acceptedFiles, rejectedFiles) {
// do some stuff here...
this.setState({ status: status.preview });
}
My render method is a three step process:
1. the actual render methos
render() {
const config = {
iconFiletypes: ['.xlsx'],
showFiletypeIcon: true,
};
return (
<div style={{ marginBottom: '30px' }}>
<Dropzone
config={config}
onDrop={files => this.onDrop(files)}
//className="dropzone"
multiple={false}
>
{this.renderDropZoneContent()}
</Dropzone>
</div>
);
}
choose what to render based on state:
renderDropZoneContent() {
switch (this.state.status) {
case status.ready:
return this.renderReadyState();
case status.preview:
return this.renderPreviewState();
// and on down for each state / status + default case...
}
}
and finally the code to render each case as functions:
renderPreviewState() {
return (
<div style={{ marginTop: '35px', textAlign: 'center' }}>
<i className="far fa-file-excel" style={{ verticalAlign: 'middle', fontSize: '50px' }} />
{/* There is more jsx here but I removed it for clarity */}
</div>
);
}
renderReadyState() {
return (
<div style={{ marginTop:'35px', textAlign:'center'}>
<i className="fas fa-cloud-upload-alt" style={{ verticalAlign: 'middle', fontSize: '50px' }} />
</div>
);
}
Nothing too crazy. My problem is that as the state changes, the text updates but the icon does not. This is an interesting problem because the logic of the application works, but its the specific element that does not get updated. Even more interesting is that I tried wrapping the entire return in another div and got the error: Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. I'm banging my head against the wall. If anyone has come across this before and have any tips it is greatly appreciate!!
Probably a conflict with how Font Awesome and React handle rendering.
If you are using React we recommend the react-fontawesome package or Web Fonts with CSS.
https://fontawesome.com/how-to-use/on-the-web/using-with/react

Resources