WebpackError: window is not defined - reactjs

I am experiencing the same issue here, Coverflow works fine for gatsby develop but for build it throws an error:
WebpackError: window is not defined
WebpackError: window is not defined
- react-coverflow.js:1 Object.<anonymous>
~/react-coverflow/dist/react-coverflow.js:1:330
- main.js:1 Object.<anonymous>
~/react-coverflow/main.js:1:1
I think it is caused by the this library "Coverflow"
import Coverflow from 'react-coverflow';
import { StyleRoot } from 'radium'
class Team extends React.Component {
render(){
return(
<StyleRoot>
<Coverflow
displayQuantityOfSide={2}
navigation
infiniteScroll
enableHeading
active={0}
media={{
'#media (max-width: 720px)': {
width: '100%',
height: '200px'
},
'#media (min-width: 720px)': {
width: '100%',
height: '400px',
}
}}
>
<img src={Sandiso} alt='Chairperson'/>
<img src={Sihle} alt='Deputy Chairperson' />
<img src={olwethu} alt='General Secretary' />
<img src={Aphiwe} alt='Recording Secretary'/>
<img src={cynoh} alt='Treasury'/>
<img src={aso} alt='Marketing' />
</Coverflow>
</StyleRoot>
)
}
}
export default Team;

Haven't looked fully into the other suggested answer re: React.Lazy and Suspense, but ran up against a similar problem trying to instantiate Intersection Observer and found a simpler answer in Kyle Matthew's response to this issue:
https://github.com/gatsbyjs/gatsby/issues/309#issuecomment-223360361
That is—potentially, you can import your package or whatever is looking for window in the componentDidMount method (or a useEffect hook) of your component.

The package 'react-coverflow' is probably expecting itself to be run on browser, which is why gatsby yells at you when it tries to render the component on server side. If you're using Gatsby v2 which seems to ship with react^16.6, you could dynamically load the component with React's lazy and Suspense combo:
// src/components/coverflow.js
import React from 'react'
import Coverflow from 'react-coverflow'
export default () => (
<Coverflow>
{/* your coverflow setup */}
</Coverflow>
)
Then you can lazy load the component on a page like this:
// src/pages/index.js
const LazyCoverflow = () => {
if (typeof window === 'undefined') return <span>loading...</span>
const Component = lazy(() => import('../components/coverflow'))
return (
<>
<Suspense fallback={<span>loading...</span>}>
<Component />
</Suspense>
</>
)
}
export default () => (
<Layout>
{/* other components */}
<LazyCoverflow />
</Layout>
)
Check out the lazy & Suspense doc on reactjs.org.

Related

react typescript stitches css prop problem, not work

i'm currently working on a project using stitches with cra but i've stuck to a problem with css props.
here's my code
Texts/index.tsx
import React from 'react';
import { TextStyle } from './textStyle';
const Texts = ({ text, css }: PropsType) => {
console.log(css);
return (
<>
<TextStyle css={{ ...css }} >
<>{text}</>
</TextStyle>
</>
);
};
export default Texts;
and this index.tsx is exported to another components
Container/index.tsx
import { styled, css } from '../../../stitches.config';
// atoms
import Texts from 'src/components/atoms/texts';
const PageContainer = () => {
return (
<Container>
<Contents >
<div>
<Texts
css={{ color: 'red' }}
/>
<Texts
css={{ paddingTop: '20px' }}
/>
</div>
</Contents>
</Container>
);
};
export default PageContainer;
as you can see with the above code, contains css as its child but css is never rendered at all
can anyone help me with this issue?
FYI, console.log(css); returned undefined to me.
Thank you in advance!

Correct use of ReactToPrint?

The problem is that the button that is supposed to give the option to print is not working anymore.
the error in the console says:
To print a functional component ensure it is wrapped with `React.forwardRef`, and ensure the forwarded ref is used. See the README for an example: https://github.com/gregnb/react-to-print#examples
I Have already seen some solutions specifically talking about the same problem but I have not been able to make it work.
any suggestion?
this is the library i'm using: ReactToPrint npm
React To print
import { useRef } from "react";
import { useReactToPrint } from "react-to-print";
import Resume from "./Pdf/Pdf";
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current
});
return (
<div >
<button onClick={handlePrint}> ------> NOT WORKING!
Descargar Pdf
</button>
<Resume ref={componentRef} /> ------> COMPONENT TO PRINT
</div>
);
};
export default Example;
Component to be printed
import React from "react";
import styled from 'styled-components';
import PdfSection from './PdfSection';
import AlienLevel from './AlienLevel';
import {connect } from 'react-redux';
class Resume extends React.Component {
renderList = () => {
return this.props.posts.diagnose.map((post) => {
return (
<PdfSection
key={post.id}
id={post.id}
divider={"/images/pdf/divider.png"}
img={"/images/alienRandom.png"}
title={post.title}
// data={post.data}
text={post.text0}
subtext={post.subtext0}
/>
);
});
};
render(){
return (
<div>
<Container>
<Page>
<Portada>
<img id="portada" src="/images/pdf/PortadaPdf.png" />
</Portada>
</Page>
<Page>
<AlienLevel
result= "{props.diagn}{"
character={"/images/pdf/alienMedio.png"}
fileName={"responseBody[4].data"}
level={"/images/pdf/level6.png"}
correct={"/images/pdf/correct.png"}
medium={"/images/pdf/medium.png"}
incorrect={"/images/pdf/incorrect.png"}
text='"Necesitas mejorar tus prácticas intergalácticas de CV, pero ya eres nivel medio!"'
/>
<div>{this.renderList()}</div>
</Page>
</Container>
</div>
);
};
}
const mapStateToProps = (state) => {
return { posts: state.posts };
};
export default connect(mapStateToProps)( Resume);
thanks in advance!
The problem is with connect() function of react-redux.
You wrapped your component in connect and connect by default does not forward ref. Which means, the ref you are passing here <Resume ref={componentRef} /> does not reach to your component.
You need to pass options { forwardRef: true } in fourth parameter of connect function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?).
Just change this code export default connect(mapStateToProps)(Resume); in Resume component to this
export default connect(mapStateToProps, null, null, { forwardRef: true })(Resume);
For anyone that is struggling with the same error, it seems that they found the proper way to resolve this, I actually resolved it by following the Codesandbox I found in the Github issues here si the link. hope is useful! -->
LINK TO GITHUB SPECIFIC ISSUE (SOLVED!!)
I had the same issue and I am happy to share my findings as soon as now.
The component has to be rendered somewhere using ref.
I added it to my page as hidden using React Material UI's Backdrop. Or u can hide it using hooks like examples below.
Using backdrop and only calling it when I need to preview the print. 👇👇
<Backdrop sx={{ color: "#fff", zIndex: (theme) => theme.zIndex.drawer + 1 }}
open={openBD}>
<ComponentToPrint ref={componentRef} />
</Backdrop>
Using Hooks plus display styling to only display it when needed. 👇👇
const [isReady, setIsReady] = useState("none");
<Paper style={{ display: isReady }} >
<ComponentToPrint ref={componentRef} />
</Paper>
<Button
variant="contained"
endIcon={<BackupTableRoundedIcon />}
onClick={() => setIsReady("")}
>
Start Printing
</Button>
Note: I used MUI components, if u decide to copy paste, then change Button to html <button and paper to <div. Hope this helps.

Basic Gatsby Shopify example missing Layouts

I am working with a basic Gatsby Shopify website template here https://www.gatsbyjs.com/docs/building-an-ecommerce-site-with-shopify/
I am trying to get this simple example up and running but I noticed in the following code block in
/src/pages/products.js
import Layout from "../components/layout"
there is no mention of components or layouts in the article and the app is throwing errors there. I am just trying to get a basic example to work. Is there a github link for this code?
The <Layout> component is a common resource in mostly all Gatsby starters (the default one for example), if you don't have it, just create the following structure under /components folder (to keep your code structure):
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.com/docs/use-static-query/
*/
import React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `0 1.0875rem 1.45rem`,
}}
>
<main>{children}</main>
<footer style={{
marginTop: `2rem`
}}>
© {new Date().getFullYear()}, Built with
{` `}
Gatsby
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
As you can see, the <Layout> component wraps the whole application with the children prop, sharing a <Header> component and a <footer> tag across all the applications when used.
You can remove propTypes if you are not using them.

Initialize script in componentDidMount – runs every route change

I am working on a navbar for my react app (using gatsbyjs to be precise). In the navbar I have a marquee that I initialize in the navbar component in componentDidMount.
It works as intended, but upon every route change componentDidMount will run again which results in the marquee speeding up for every page change, making it go faster and faster.
Is this expected behaviour? And if so, how do I make sure that the script is only run once?
navbar.js
import React from 'react';
import { Link } from 'gatsby';
import styles from '../styles/navbar.module.css';
import NewsMarquee from './newsMarquee';
import Marquee3k from 'marquee3000';
const topLevelNav = [
{
href: '/news',
label: <NewsMarquee/>,
extraClass: styles.navLinkNews,
mediaQueryClass: styles.navLinkHiddenSmall,
},
];
export default class Navbar extends React.Component {
componentDidMount() {
Marquee3k.init();
}
render() {
return (
<div>
<header className={styles.navbar} role="banner">
<nav className={styles.nav}>
{topLevelNav.map(({ href, label, extraClass = '', mediaQueryClass = '' }) => (
<Link
key={label}
to={href}
className={`${styles.navLink} ${extraClass} ${mediaQueryClass} ${menuItemsHidden}`}
activeClassName={styles.navLinkActive}
>
{label}
</Link>
))}
</nav>
</header>
</div>
)
}
}
newsMarquee.js
import React from 'react';
import { StaticQuery, graphql } from "gatsby";
import styles from '../styles/newsMarquee.module.css';
export default () => (
<StaticQuery
query={graphql`
query {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC } limit: 10) {
totalCount
edges {
node {
id
frontmatter {
title
date(formatString: "YYYY.MM.DD")
}
fields {
slug
}
}
}
}
}
`}
render={data => (
<div className={`marquee3k ${styles.marquee}`}>
<div>
{data.allMarkdownRemark.edges.map(({ node }) => (
<span className={styles.marqueeItem} key={node.id}>
{node.frontmatter.date} {node.frontmatter.title}
</span>
))}
</div>
</div>
)}
/>
)
Since I'm using GatsbyJS I went with this plugin from V1, which makes my layout component persist across pages.
gatsby-plugin-layout
This plugin enables adding components which live above the page components and persist across page changes.
This can be helpful for:
Persisting layout between page changes for e.g. animating navigation
Storing state when navigating pages
Custom error handling using componentDidCatch
Inject additional data into pages using React Context.
This plugin reimplements the behavior of layout components in gatsby#1, which was removed in version 2.

React Native : Custom Tabbar

React native : How can I custom tab bar like image below??
1) you can use this library to create tabs react-native-scrollable-tab-view.
2) Then it has a prop (renderTabBar) here you can pass your own custom tab bar.
<ScrollableTabView renderTabBar={() => <DefaultTabBar tabStyle={{color: 'red'}} />} />
one tip that i am giving.
make a file name it CustomTabBar copy all the code from libraries DefaultTabBar and past it in your CustomTabBar.
now change its designs the way you want it to be and use it like this. This way you will have to do the least amount of work.
<ScrollableTabView renderTabBar={() => <CustomTabBar/>} />
Maybe this is the solution you need
1, Install: switch-react-native
npm i switch-react-native
2, Using lib:
import React, { Component } from 'react';
import { View } from 'react-native';
import { Switch } from 'switch-react-native';
class SwitchExample extends Component {
render() {
return (
<View>
<Switch
height={40}
width={300}
activeText={`Active Text`}
inActiveText={`InActive Text`}
onValueChange={(value: any) => console.log(value)}
/>
</View>
);
}
}

Resources