StaticImage not showing up in test render in Gatsby - javascript

I have been searching through google for this for about an hour and have decided that I will likely need more direct assistance instead of just looking at other people's post.
My goal is to be able to have a jest test using this library https://github.com/testing-library/react-testing-library to be able to use the 'render' function and check that a StaticImage component inside of a custom component is rendered.
Currently this is my NavBar.tsx:
import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';
import Test from '../Test/Test';
const NavBar: React.FC = () => {
return (
<nav data-testid="nav-bar">
<Test siteTitle="TestssS" />
<StaticImage src="../../images/logo.png" alt="Logo" />
</nav>
);
};
export default NavBar;
And this is my NavBar.test.tsx:
import React from 'react';
import { render } from '#testing-library/react';
import NavBar from './NavBar';
describe('Ensuring NavBar is Rendered', () => {
test('Ensuring Navbar is in the page', () => {
const { getByTestId } = render(<NavBar />);
expect(getByTestId('nav-bar')).toBeInTheDocument();
});
});
describe('Squarehook logo is inside navbar', () => {
test('Ensure Logo is in Navbar', async () => {
const { getByAltText } = await render(<NavBar />);
expect(getByAltText('Logo')).toBeInTheDocument;
});
});
The test I am talking about is the 'Ensure Logo is in Navbar' test at the bottom. Ideally, I'd be rendering the NavBar component which would have the StaticImage component. Theoritically once StaticImage has completed rendering there would be an img tag with the alt attribute of 'Logo'.
However once I run npm test I get this result:
TestingLibraryElementError: Unable to find an element with the alt text: Logo
Ignored nodes: comments, <script />, <style />
<body>
<div>
<nav
data-testid="nav-bar"
>
<h1
class="header"
data-testid="test"
>
TestssS
</h1>
</nav>
</div>
</body>
13 | test('Ensure Logo is in Navbar', async () => {
14 | const { getByAltText } = await render(<NavBar />);
> 15 | expect(getByAltText('Logo')).toBeInTheDocument;
| ^
16 | });
17 | });
18 |
at Object.getElementError (node_modules/#testing-library/dom/dist/config.js:38:19)
at node_modules/#testing-library/dom/dist/query-helpers.js:90:38
at node_modules/#testing-library/dom/dist/query-helpers.js:62:17
at getByAltText (node_modules/#testing-library/dom/dist/query-helpers.js:111:19)
at Object.<anonymous> (src/compontents/NavBar/NavBar.test.tsx:15:12)
You can see from the log above that the nav and the Test component get rendered, but for some reason there is no StaticImage/Img element at this point in time. I was reading a resource that said I may have needed to add await to those commands so I tried that on all of them but without any success.
I am using Gastby with Typescript.
the packages that are related to this is the
gatsby-plugin-image and the #testing-library/react.
I appreciate any help in advance!

Related

How can I customize the style of a React component shared between lazy-loaded pages?

I'm building a React application and I started using CRA. I configured the routes of the app using React Router. Pages components are lazy-loaded.
There are 2 pages: Home and About.
...
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
...
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/about" component={About} />
<Route path="/" component={Home} />
</Switch>
</Suspense>
...
Each page uses the Button component below.
import React from 'react';
import styles from './Button.module.scss';
const Button = ({ children, className = '' }) => (
<button className={`${styles.btn} ${className}`}>{children}</button>
);
export default Button;
The Button.module.scss file just sets the background color of the button to red.
.btn {
background: red;
}
The Button component accepts a className prop which is then added to the rendered button. This is because I want to give freedom to the consumer of the component. For example, in some pages margins could be needed or the background should be yellow instead of red.
To make it simple, I just want to have a different background color for the Button based on the current page, so that:
Home page => Blue button
About page => Yellow button
Each page is defined as below:
import React from 'react';
import Button from './Button';
import styles from './[PageName].module.scss';
const [PageName] = () => (
<div>
<h1>[PageName]</h1>
<Button className={styles.pageBtn}>[ExpectedColor]</Button>
</div>
);
export default [PageName];
where [PageName] is the name of the page and [ExpectedColor] is the corresponding expected color based on the above bullet list (blue or yellow).
The imported SCSS module, exports a class .pageBtn which sets the background property to the desired color.
Note: I could use a prop on the Button component which defines the variant to display (Blue/Yellow) and based on that prop add a class defined in the SCSS file. I don't want to do that since the change could be something that doesn't belong to a variant (e.g. margin-top).
The problem
If I run the application using yarn start, the application works fine. However, if I build the application (yarn build) and then I start serving the application (e.g. using serve -s build), the behavior is different and the application doesn't work as expected.
When the Home page is loaded, the button is correctly shown with a blue background. Inspecting the loaded CSS chunk, it contains:
.Button_btn__2cUFR {
background: red
}
.Home_pageBtn__nnyWK {
background: blue
}
That's fine. Then I click on the navigation link to open the About page. Even in this case, the button is shown correctly with a yellow background. Inspecting the loaded CSS chunk, it contains:
.Button_btn__2cUFR {
background: red
}
.About_pageBtn__3jjV7 {
background: yellow
}
When I go back to the Home page, the button is now displayed with a red background instead of yellow. That's because the About page has loaded the CSS above which defines again the Button_btn__2cUFR class. Since the class is now after the Home_pageBtn__nnyWK class definition, the button is displayed as red.
Note: the Button component is not exported on the common chunk because its size is too small. Having that in a common chunk could solve the problem. However, my question is about small shared components.
Solutions
I have thought to 2 solutions which, however, I don't like too much:
Increase selectors specificity
The classes specified in the [PageName].module.scss could be defined as:
.pageBtn.pageBtn {
background: [color];
}
This will increase the selector specificity and will override the default Button_btn__2cUFR class. However, each page chunk will include the shared components in case the component is quite small (less than 30kb). Also, the consumer of the component has to know that trick.
Eject and configure webpack
Ejecting the app (or using something like react-app-rewired) would allow specifying the minimum size for common chunk using webpack. However, that's not what I would like for all the components.
To summarize, the question is: what is the correct working way of overriding styles of shared components when using lazy-loaded routes?
You can use the following logic with config file for any pages. Also, You can send config data from remote server (req/res API) and handle with redux.
See Demo: CodeSandBox
create components directory and create files like below:
src
|---components
|---Button
| |---Button.jsx
| |---Button.module.css
Button Component:
// Button.jsx
import React from "react";
import styles from "./Button.module.css";
const Button = props => {
const { children, className, ...otherProps } = props;
return (
<button className={styles[`${className}`]} {...otherProps}>
{children}
</button>
);
};
export default Button;
...
// Button.module.css
.Home_btn {
background: red;
}
.About_btn {
background: blue;
}
create utils directory and create AppUtils.js file:
This file handle config files of pages and return new object
class AppUtils {
static setRoutes(config) {
let routes = [...config.routes];
if (config.settings) {
routes = routes.map(route => {
return {
...route,
settings: { ...config.settings, ...route.settings }
};
});
}
return [...routes];
}
static generateRoutesFromConfigs(configs) {
let allRoutes = [];
configs.forEach(config => {
allRoutes = [...allRoutes, ...this.setRoutes(config)];
});
return allRoutes;
}
}
export default AppUtils;
create app-configs directory and create routesConfig.jsx file:
This file lists and organizes routes.
import React from "react";
import AppUtils from "../utils/AppUtils";
import { pagesConfig } from "../pages/pagesConfig";
const routeConfigs = [...pagesConfig];
const routes = [
...AppUtils.generateRoutesFromConfigs(routeConfigs),
{
component: () => <h1>404 page not found</h1>
}
];
export default routes;
Modify index.js and App.js files to:
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
rootElement
);
...
react-router-config: Static route configuration helpers for React
Router.
// App.js
import React, { Suspense } from "react";
import { Switch, Link } from "react-router-dom";
import { renderRoutes } from "react-router-config";
import routes from "./app-configs/routesConfig";
import "./styles.css";
export default function App() {
return (
<div className="App">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<Suspense fallback={<h1>loading....</h1>}>
<Switch>{renderRoutes(routes)}</Switch>
</Suspense>
</div>
);
}
create pages directory and create files and subdirectory like below:
src
|---pages
|---about
| |---AboutPage.jsx
| |---AboutPageConfig.jsx
|
|---home
|---HomePage.jsx
|---HomePageConfig.jsx
|
|---pagesConfig.js
About Page files:
// AboutPage.jsx
import React from "react";
import Button from "../../components/Button/Button";
const AboutPage = props => {
const btnClass = props.route.settings.layout.config.buttonClass;
return (
<>
<h1>about page</h1>
<Button className={btnClass}>about button</Button>
</>
);
};
export default AboutPage;
...
// AboutPageConfig.jsx
import React from "react";
export const AboutPageConfig = {
settings: {
layout: {
config: {
buttonClass: "About_btn"
}
}
},
routes: [
{
path: "/about",
exact: true,
component: React.lazy(() => import("./AboutPage"))
}
]
};
Home Page files:
// HomePage.jsx
import React from "react";
import Button from "../../components/Button/Button";
const HomePage = props => {
const btnClass = props.route.settings.layout.config.buttonClass;
return (
<>
<h1>home page</h1>
<Button className={btnClass}>home button</Button>
</>
);
};
export default HomePage;
...
// HomePageConfig.jsx
import React from "react";
export const HomePageConfig = {
settings: {
layout: {
config: {
buttonClass: "Home_btn"
}
}
},
routes: [
{
path: "/",
exact: true,
component: React.lazy(() => import("./HomePage"))
}
]
};
...
// pagesConfig.js
import { HomePageConfig } from "./home/HomePageConfig";
import { AboutPageConfig } from "./about/AboutPageConfig";
export const pagesConfig = [HomePageConfig, AboutPageConfig];
Edited section:
With HOC Maybe this way: CodeSandBox
create hoc dir and withPage.jsx file:
src
|---hoc
|---withPage.jsx
...
// withPage.jsx
import React, { useEffect, useState } from "react";
export function withPage(Component, path) {
function loadComponentFromPath(path, setStyles) {
import(path).then(component => setStyles(component.default));
}
return function(props) {
const [styles, setStyles] = useState();
useEffect(() => {
loadComponentFromPath(`../pages/${path}`, setStyles);
}, []);
return <Component {...props} styles={styles} />;
};
}
And then pages like below:
src
|---pages
|---about
| |---About.jsx
| |---About.module.css
|
|---home
|---Home.jsx
|---Home.module.css
About.jsx file:
// About.jsx
import React from "react";
import { withPage } from "../../hoc/withPage";
const About = props => {
const {styles} = props;
return (
<button className={styles && styles.AboutBtn}>About</button>
);
};
export default withPage(About, "about/About.module.css");
About.module.css file:
// About.module.css
.AboutBtn {
background: yellow;
}
Home.jsx file:
// Home.jsx
import React from "react";
import { withPage } from "../../hoc/withPage";
const Home = props => {
const { styles } = props;
return <button className={styles && styles.HomeBtn}>Home</button>;
};
export default withPage(Home, "home/Home.module.css");
Home.module.css file:
// Home.module.css
.HomeBtn {
background: red;
}
I would suggest instead of adding both the default styles and the consumer styles, use the consumer's styles over yours and use your as a callback if not supplied. The consumer can still compose your defaults with the composes keyword.
Button.js
import React from 'react';
import styles from './Button.module.scss';
const Button = ({ children, className}) => (
<button className={className ?? styles.btn}>{children}</button>
);
export default Button;
SomePage.module.scss
.pageBtn {
// First some defaults
composes: btn from './Button.module.scss';
// And override some of the defautls here
background: yellow;
}
If you wish, use sass #extends or #mixin instead
EDIT: Haven't tested it, but could it be that just by using composes webpack will make sure to bundle the defaults only once? Thus you're no longer needed to change your Button.js code with the ??
Solution 1
I know this is very obvious, but would work anyway:
Set !important on your overwriting css rules, thus bypassing specificity:
[PageName].module.scss:
.btn {
color: yellow !important;
}
However, most of the strict devs I know would avoid this keyword at all cost.
Why ?
Because when you start to have a lot of !important your css is a nightmare to debug. If you start writing !important rules with higher specificity, you know you have gone too far
It is only meant for corner-cases like yours, you might as well use it.
Solution 2
fix CRA config to enforce style tags order.
It is open-source after all :)
You can give your input on this bug here (upvote might give it more visibility):
https://github.com/facebook/create-react-app/issues/7190
Solution 3 (Update)
You could create a SCSS mixin in a new customButton.scss file, to generate css rules with higher specificity:
// customButton.scss
#mixin customBtn() {
:global {
.customBtn.override {
#content;
}
}
}
We will use two static class names (using the :global selector), because that way their name won't change based on where they are imported from.
Now use that mixin in your pages' SCSS:
// [pageName].module.scss
#import 'customButton.scss';
#include customBtn {
color: yellow;
}
css output should be:
.customBtn.override {
// put everything you want to customize here
color: yellow;
}
In Button.jsx: apply both class names to your button in addition to styles.btn:
// Button.jsx
const Button = ({ children, className = '' }) => (
<button className={`${styles.btn} customBtn override ${className}`}>
{children}
</button>
);
(Note that these are not referenced through the styles object, but the classname directly)
The main drawback is these are not dynamic class names, so you have to watch out to avoid conflicts yourself like we use to do before.
But I think it should do the trick

React js - make button link to a different app

I want to make a button to link to a different app with react librery.
my code looks like this
import React, { Component } from "react";
import { Link, NavLink, Redirect } from "react-router-dom";
import "./subportfolio.scss";
import Coffee1 from "../../assets/coffee-1.jpg";
import Coffee2 from "../../assets/coffee-2.jpg";
import Coffee3 from "../../assets/coffee-3.jpg";
import Coffee4 from "../../assets/coffee-4.jpg";
import CoffeeShop from "../../assets/coffee-shop-1.jpg";
import Tea1 from "../../assets/tea-1.jpg";
import Tea2 from "../../assets/tea-2.jpg";
import Tea3 from "../../assets/tea-3.jpg";
class SubPortfolio extends Component {
state = {
projectImg: {
project1: Coffee1,
project2: Coffee2,
project3: Coffee3,
project4: Coffee4,
project5: CoffeeShop,
project6: Tea1,
project7: Tea2,
project8: Tea3
},
direct: ""
};
directToGithub = () => {
this.props.history.go("https://github.com");
};
render() {
console.log(this.state.direct);
return (
<div className="subPortfolio">
<div className="subPortfolio__content">
<div className="subPortfolio__content--detail">
<h2>Image Format</h2>
<div className="subPortfolio__content--refer">
<div className="subPortfolio__content--button">
<button
id="github"
type="button"
onClick={this.directToGithub}
>
github
</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default SubPortfolio;
I tried all of the history properties but all of them throw an error
TypeError: Cannot read property 'go' of undefined
SubPortfolio.directToGithub
C:/Users/Ermais Kidane/Documents/REACT/portfolio/src/components/subportfolio/subportfolio.js:30
27 | };
28 |
29 | directToGithub = () => {
> 30 | this.props.history.go("https://github.com");
| ^ 31 | };
32 | render() {
33 | // const projectsImage = Object.keys(this.state.projectImg).map(proImg => {
I tried using Link React-router-dom and to adds to with the previous url like (http://localhost:3000/https://github.com) and does not take make anywhere.
how could I make the link to another web site? thanks for your help.
If you are trying to get directed to an external website, just use the standard <a></a> tag
<button id="github" type="button">github</button>
if you are trying to use the <Link> to get directed to an internal link, it would look more like this
<Link to="/github"><button id="github" type="button">github</button></Link>
And the link would then have to be setup in the app.js using the router to then be directed to the named component
If you want to programmatically direct to an external website, you can also use window.location = "https://github.com" or, assuming a global window object, location = "https://github.com".

Stuck at "Cannot read property 'props' of undefined"

I'm testing out the gatsby-source-wordpress plugin from Gatsby, and I'm trying to get my menu to fetch the links from my Wordpress site.
I've managed to get all of the Wordpress schemas to come up in GraphiQL, and copied the GQL code from there.
I've made a Layout component, where I've tried most of what I can to make it work. However, I keep getting TypeError: Cannot read property 'props' of undefined when I deploy my Gatsby site to localhost.
Anyone ever come across this before? I'm kinda new to GraphQL and all that, so I honestly have no clue what's wrong, or if it's even GraphQL that's causing this. Any help is greatly appreciated! (Sorry if this is a really simple fix, and I'm just being ignorant)
I've searched through Google, Stack Overflow, Youtube, and anywhere else I could think of.
Code
Layout
import React, { Component } from "react";
import PropTypes from "prop-types";
import { StaticQuery, graphql } from "gatsby";
// import Image from "gatsby"
import Header from "../Header";
import MainMenu from "../Nav";
// import Aside from "../Aside"
// import Footer from "../Footer";
const Layout = ({ children }) => {
const menu = this.props.data.allWordpressWpApiMenusMenusItems;
return (
<StaticQuery
query={graphql`
query menuQuery {
allWordpressWpApiMenusMenusItems {
edges {
node {
id
name
items {
title
object_slug
url
}
}
}
}
}
`}
render={menu => (
<>
<Header>
<MainMenu menu="{data.allWordpressWpApiMenusMenusItems}" />
</Header>
<div className="Layout">
<main>{children}</main>
</div>
<footer>Footer</footer>
</>
)}
/>
);
};
Layout.propTypes = {
children: PropTypes.node.isRequired
};
export default Layout;
Menu component
import React, { Component } from "react";
// import { Link } from "gatsby";
class MainMenu extends Component {
render() {
const data = this.props.data.allWordpressWpApiMenusMenusItems;
console.log(data);
return (
<nav className="main-menu">
<ul>
<p>Test</p>
</ul>
</nav>
);
}
}
export default MainMenu;
Expected result: The site renders on localhost:8000
Error messages I recieve:
src/components/Layout/index.js:11
8 | // import Aside from "../Aside"
9 | // import Footer from "../Footer";
10 |
> 11 | const Layout = ({ children }) => {
12 | const menu = this.props.data.allWordpressWpApiMenusMenusItems;
13 | return (
14 | <StaticQuery
You're accessing this.props in a function based component. Change your declaration to
const Layout = ({ children, data }) => {
const menu = data.allWordpressWpApiMenusMenusItems;
Or explicitly declare props and destructure the properties you want
const Layout = props => {
const { data, children, ...rest } = props
const menu = data.allWordpressWpApiMenusMenusItems;

How to resolve this "Target container is not a DOM element." in React with React-Image Gallery/Lightbox?

Im trying to find a solution to what Ive been experiencing with image based galleries (in example lightbox or FancyBox). This error came up after following this doc and using this code as an
example.
I have tried using react-images to no avail, the modal doesn't display right, so I tried the links react-photo-gallery and I am encountering this error. Ive tried converting it to a component, and it didn't agree with the App function in the top portion of the file. I also tried creating a html file in my pages directory and added the import link to the illustrationGallery file, but that didn't seem to work.
My illustrationGallery file
import React, { useState, useCallback } from "react";
import { render } from "react-dom";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
import { illustrations } from "../components/illustrations";
import Artwork from '../pages/gallery';
function App() {
const [currentImage, setCurrentImage] = useState(0);
const [viewerIsOpen, setViewerIsOpen] = useState(false);
const openLightbox = useCallback((event, { photo, index }) => {
setCurrentImage(index);
setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setViewerIsOpen(false);
};
return (
<div>
<Gallery illustrations={illustrations} onClick={openLightbox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightbox}>
<Carousel
currentIndex={currentImage}
views={illustrations.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
render(<App />, document.getElementById("illuGallery"));
Local host window error
invariant
node_modules/react-dom/cjs/react-dom.development.js:56
render
node_modules/react-dom/cjs/react-dom.development.js:21195
▲ 2 stack frames were expanded.
Module.<anonymous>
src/components/illustrationGallery.js:43
40 | </div>
41 | );
42 | }
> 43 | render(<App />, document.getElementById("illuGallery"));
44 |
This error description is towards the top, but there are more
Just trying to achieve something that displays a proper image gallery using react, would it be easier to just make it using another doc or from scratch? Does anyone have any recommendations or answers to help?
This happens because:
document.getElementById("illuGallery") can not find an element with id #illuGaller.
if you are willing to make it work, and this is the only component you actually want react to render.
as from the example of the codesandbox project.
You go to your template, where react renders the ellement. basically index.html or template.html, in the example it's index.html
And make sure that the root element there which where react will inject your JSX, make sure it has the id illuGallery

Dynamically rendered Tag is always lowercase

I am trying to output some svgs and output them from a list, here is my render method:
render() {
const renderTag = () => {
const Tag = this.props.id
return(<Tag />)
}
return (
<div key={this.props.name} className="social-box">
<a className={this.props.id + "-link"}>
{renderTag()}
</a>
</div>
)
}
However, the DOM node is always lowercase i.e. <facebook> rather than <Facebook> this.props.id is correctly rendered to the console as Facebook. Can anyone tell me why react or the browser incorrectly renders as lowercase, and therefore not the component, and how to fix?
It's a technical implementation of React, all tags get lowercased on this line here, AFAIK it's not possible to render non-lowercased tags and that is by design.
Read more here.
i suggest that you would take a look at this article about dynamic components.
The most relevant example from the article:
import React, { Component } from 'react';
import FooComponent from './foo-component';
import BarComponent from './bar-component';
class MyComponent extends Component {
components = {
foo: FooComponent,
bar: BarComponent
};
render() {
const TagName = this.components[this.props.tag || 'foo'];
return <TagName />
}
}
export default MyComponent;
you most likely have a limited amount of components that could be rendered, so you might create a dictionary that contain a key (name of the component) to the component itself (as shown in the example) and just use it that way:
import Facebook from './FaceBook';
import Twitter from './Twitter';
const components = {
facebook: Facebook,
twitter: Twitter
};
render() {
return <div key={this.props.name} className="social-box">
<a className={this.props.id + "-link"}>
<components[this.props.id] />
</a>
</div>;
}
I find the answer eventually. #TomMendelson almost had the answer, but it needed fleshing out a bit more.
A function to create the component outside of the render method, suggested by #ShubhamKhatri actually did the job. Here's the final code:
import React from 'react';
import Facebook from './svg/Facebook';
import LinkedIn from './svg/LinkedIn';
import Twitter from './svg/Twitter';
import Pinterest from './svg/Pinterest';
class SocialMediaBox extends React.Component {
renderElement(item) {
const Components = {
'Facebook': Facebook,
'Twitter': Twitter,
'Pinterest': Pinterest,
'LinkedIn': LinkedIn
}
return React.createElement(Components[item], item);
}
render() {
const Element = this.renderElement(this.props.id)
return
(
<div>
{Element}
</div>
)
}
}
export default SocialMediaBox;
Thanks for the question and answers; alongside the answers given in Dynamic tag name in jsx and React they helped me to find a solution in my context (making a functional component in Gatsby with gatsby-plugin-react-svg installed):
import React from "react"
import FirstIcon from "../svgs/first-icon.inline.svg"
import SecondIcon from "../svgs/second-icon.inline.svg"
import ThirdIcon from "../svgs/third-icon.inline.svg"
const MyComponent = () => {
const sections = [
{ heading: "First Section", icon: () => <FirstIcon /> },
{ heading: "Second Section", icon: () => <SecondIcon /> },
{ heading: "Third Section", icon: () => <ThirdIcon /> },
]
return (
<>
{sections.map((item, index) => {
const Icon = item.icon
return (
<section key={index}>
<Icon />
<h2>{item.heading}</h2>
</section>
)
})}
</>
)
}
export default MyComponent
As mine is a Gatsby project I used the above mentioned plugin, but it itself process svgs with svg-react-loader so the basic principle should work in any React project using this package.

Categories

Resources