Gatsby.js problem with <Link>, no matter what I try - javascript

I've a serious issue with the built-in <Link> component in Gatsby.js. I'm building a huge web project and everything was fine until I've tried to use <Link> instead of the standard <a> tag. I was frustrated to the point that I created a brand new, a blank project to test <Link> on a completely fresh project. Below you'll find the code. I'm trying to get from the index page to the contact page:
Index Page:
import React from "react"
import {Link} from "react"
const IndexPage = () => {
return (
<div>
<p>Link Test</p>
Anchor to Contact
<Link to="/contact/">Link to Contact</Link>
</div>
)
}
export default IndexPage
Contact page:
import React from "react"
const Contact = () => {
return (
<div>
<p>Contact page</p>
</div>
)
}
export default Contact;
When I use <a> tag everything is working smoothly but immediately after I'm trying to add <Link> in code I'm getting the same stupid error. It's only showing in browser not in the terminal of visual studio.
This is the error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `IndexPage`.
▶ 21 stack frames were collapsed.
(anonymous function)
/Users/piotr/Documents/Websites/LinkTest/LinkTest/.cache/app.js:133
130 | const preferDefault = m => (m && m.default) || m
131 | const Root = preferDefault(require(`./root`))
132 | domReady(() => {
> 133 | renderer(<Root />, rootElement, () => {
134 | apiRunner(`onInitialClientRender`)
135 | })
136 | })
Please help because I've no idea what I should try next and I'm stuck on that bug for two days. Maybe I should update gatsby, node.js, and react on my computer? It's worth trying? :)

You need to import Link from Gatsby, not from React:
import { Link } from "gatsby"
Gatsby routing extends from #reach/router (from React) but it adds useful enhancements specific to Gatsby, so it should be imported as a Gatsby dependency. All props are passed through to #reach/router’s Link component.
Keep in mind that, using a built-in anchor tag will refresh the whole page and the whole components (header, footer, etc), it won't be caught by the #reach/router.
While using Link component, it will only refresh the needed components, adding a more smooth behavior.

Related

adding a .client suffix to my .jsx or .tsx file breaks the import in Remix

I'm ultimately trying to get remix-utils to help me render a client-side-only component. Was lead to believe that a .client.tsx or .client.jsx file would help (even though I can't find it in the docs anywhere)
So I have this file:
// app/components/Test.client.jsx
export default function Test() {
return <div>This is a test</div>;
}
being imported into my index.tsx file:
// app/routes/index.tsx
import Test from "~/components/Test.client";
export default function Index() {
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.4" }}>
<h1>Welcome to Remix</h1>
<Test />
</div>
);
}
Why won't this work? I've done this exact setup in a vanilla TypeScript app, and it works fine. Also, if I just remove the .client suffix it will import fine, but adding .client at the end of the file name somehow breaks the app and produces this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The .client suffix tells Remix to only include this in the client bundle.
Remember that Remix will render your route component on both the server and the client. By making Test a client-only component, it breaks if your route is server rendered (Test is essentially undefined on the server).
If the component is truly client only, then you also need to use the <ClientOnly/> wrapper from remix utils.
<ClientOnly>
{() => <Test/>}
</ClientOnly>
This ensures that Remix does not try to render the component server-side.

Gatsby's StaticImage not rendering in Storybook

I'm trying to write a storybook for my component with Gatsby's StaticImage but this ends up in nothing at all rendered and an error disguised as warning in the console:
Please ensure that "gatsby-plugin-image" is included in the plugins array in gatsby-config.js, and that your version of gatsby is at least 2.24.78
(anonymous) # static-image.server.tsx:52
I wonder if there's a way to render component using StaticImage outside of Gatsby?
Component is trivial:
import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';
export const Card = ({ title }) => {
return (
<div>
<div>{title}</div>
<StaticImage src="../../assets/images/background.png" alt="" width={300} height={100}/>
</div>
);
};
I'm using Gatsby v3 & Storybook v6.3
Based on the Gatsby Documentation, it isn't presently supported yet.
Note: Writing stories for components that use StaticImage from gatsby-plugin-image is currently not supported. Contributions to making this possible are welcome.

to show the loading bar till the fetched

I am trying to show the loading bar until it is fetched. so I chose to use the material UI loading bar. I created this method to show the loading bar renderProgressBar.
But when I was trying to render It was giving this error:
invariant.js:42 Uncaught Invariant Violation: Element type is
invalid: expected a string (for built-in components) or a
class/function (for composite components) but got: undefined. You
likely forgot to export your component from the file it's defined in,
or you might have mixed up default and named imports.
I tried debugging in the console but nothing helped.
can you tell me how to fix it by using the code snippet below?
https://codesandbox.io/s/redux-async-actions-hntd8
renderProgressBar = () => {
console.log(
'store.getState().fetchingMessage---->',
store.getState().fetchingMessage
);
if (store.getState().fetchingMessage) {
console.log(
'inside if rstore.getState().fetchingMessage---->',
store.getState().fetchingMessage
);
return (
<div
>
<LinearProgress />
</div>
);
}
};
LinearProgress is not being imported correctly that's why you are getting the Invariant Violation.
As stated here: https://material-ui.com/api/linear-progress/
You want to use either of these imports:
import LinearProgress from '#material-ui/core/LinearProgress';
// or
import { LinearProgress } from '#material-ui/core';
You seem to have import {LinearProgress} from '#material-ui/core/LinearProgress'; which doesn't return undefined because it's not exporting a named module called LinearProgress under core folder.
Hey #zf I've refactored a little of your codesandbox and i found mainly two issues:
The first one is as we said before that you are importing LinearProgress the wrong way.
The other issue that ive found is that you have unmatching versions of react and reactDOM.
Then i've just added the calls to get the clases and the styles and there you got it, check the codesandbox and feel free to ask questions:
https://codesandbox.io/s/redux-async-actions-i4vqf
Remem,ber to read the docs when you are stuck, this is the main flow to solve your issues. LinearProgressDocs

Using a Custom Title Bar in an Electron JS App

I just started using the electron-react-boilerplate and currently trying to use a custom title bar by using the electron-titlebar package which was installed using npm install --save eletron-titlebar.
Based on my very weak understanding of the electron boilerplate and electron in general, I tried what the electron-titlebar docs suggested and introduced the <TitleBar> component on the same level as the children element of the Root component, resulting in the code below.
Problem: However whenever the <TitleBar> component is there, we get a blank screen. Removing the component give us back our original DOM elements, but obviously, no title bar since we just removed it.
An error is also shown in the JS console
react-dom.development.js:55 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
What is the correct way to use electron-titlebar with the electron-react-boilerplate setup?
/app/containers/App.js
// #flow
import * as React from 'react';
import TitleBar from 'electron-titlebar';
type Props = {
children: React.Node
};
export default class App extends React.Component<Props> {
props: Props;
render() {
const { children } = this.props;
return (
<div>
<TitleBar
title="Electron"
/>
{children}
</div>
)
}
}
Just starting messing around with Electron myself and ran into this error. I was able to solve it by changing my import to require:
const TitleBar = require('frameless-titlebar');

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I am getting this error:
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
This is my code:
var React = require('react')
var ReactDOM = require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link
var App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
</ul>
</div>
)
}
})
var About = require('./components/Home')
ReactDOM.render((
<Router>
<Route path="/" component={App}>
<Route path="about" component={About} />
</Route>
</Router>
), document.body)
My Home.jsx file:
var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');
var Home = React.createClass({
render:function() {
return (
<RaisedButton label="Default" />
);
},
});
module.exports = Home;
In my case (using Webpack) it was the difference between:
import {MyComponent} from '../components/xyz.js';
vs
import MyComponent from '../components/xyz.js';
The second one works while the first is causing the error. Or the opposite.
you need export default or require(path).default
var About = require('./components/Home').default
Have you just modularized any of your React components? If yes, you will get this error if you forgot to specify module.exports, for example:
non-modularized previously valid component/code:
var YourReactComponent = React.createClass({
render: function() { ...
modularized component/code with module.exports:
module.exports = React.createClass({
render: function() { ...
In my case, one of the exported child module was not returning a proper react component.
const Component = <div> Content </div>;
instead of
const Component = () => <div>Content</div>;
The error shown was for the parent, hence couldn't figure out.
If you get this error, it might be because you're importing link using
import { Link } from 'react-router'
instead, it might be better to use
import { Link } from 'react-router-dom'
^--------------^
I believe this is a requirement for the react router version 4
Don't get surprised by the list of answers for a single question. There are various causes for this issue;
For my case, the warning was
warning.js:33 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check your code at index.js:13.
Followed by the error
invariant.js:42 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
I couldn't understand the error since it doesn't mention any method or file name. I was able to resolve only after looking at this warning, mentioned above.
I have the following line at the index.js.
<ConnectedRouter history={history}>
When I googled for the above error with the keyword "ConnectedRouter" I found the solution in a GitHub page.
The error is because, when we install react-router-redux package, by default we install this one.
https://github.com/reactjs/react-router-redux but not the actual library.
To resolve this error, install the proper package by specifing the npm scope with #
npm install react-router-redux#next
You don't need to remove the wrongly installed package. It will be automatically overwritten.
Thank you.
PS: Even warning helps you. Don't neglect warning just looking at the error alone.
Given your error of:
'Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object'
You have 2 options:
Your export file can have the word default as in
export default class someNameHere
Then your import will need to avoid using {} around it. As in
import somethingHere from someWhereHere
Avoid using the default word. Then your export looks like
export class someNameHere
Then your import must use the {}. Like
import {somethingHere} from someWhereHere
https://github.com/rackt/react-router/blob/e7c6f3d848e55dda11595447928e843d39bed0eb/examples/query-params/app.js#L4
Router is also one of the properties of react-router.
So change your modules require code like that:
var reactRouter = require('react-router')
var Router = reactRouter.Router
var Route = reactRouter.Route
var Link = reactRouter.Link
If you want to use ES6 syntax the link use(import), use babel as helper.
BTW, to make your code works, we can add {this.props.children} in the App,
like
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
</ul>
{this.props.children}
</div>
)
}
In my case, that was caused by wrong comment symbols. This is wrong:
<Tag>
/*{ oldComponent }*/
{ newComponent }
</Tag>
This is correct:
<Tag>
{/*{ oldComponent }*/}
{ newComponent }
</Tag>
Notice the curly brackets
I have the same error :
ERROR FIX !!!!
I use 'react-router-redux' v4 but she's bad..
After npm install react-router-redux#next
I'm on "react-router-redux": "^5.0.0-alpha.9",
AND IT'S WORK
I got this by doing import App from './app/'; expecting it to import ./app/index.js, but it instead imported ./app.json.
I was having the same issue and realized that I was providing an Undefined React component in the JSX markup. The thing is that the react component to render was dynamically calculated and it ended up being undefined!
The error stated:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of C.,
The example producing this error:
var componentA = require('./components/A');
var componentB = require('./components/B');
const templates = {
a_type: componentA,
b_type: componentB
}
class C extends React.Component {
constructor(props) {
super(props);
}
// ...
render() {
//Let´s say that depending on the uiType coming in a data field you end up rendering a component A or B (as part of C)
const ComponentTemplate = templates[this.props.data.uiType];
return <ComponentTemplate></ComponentTemplate>
}
// ...
}
The problem was that an invalid "uiType" was provided and therefore this was producing undefined as result:
templates['InvalidString']
Just as a quick addition to this. I was having the same problem and while Webpack was compiling my tests and the application was running fine. When I was importing my component into the test file I was using the incorrect case on one of the imports and that was causing the same error.
import myComponent from '../../src/components/myComponent'
Should have been
import myComponent from '../../src/components/MyComponent'
Note that the import name myComponent depends on the name of the export inside the MyComponent file.
Had similar issue with React Native latest versions 0.50 and up.
For me it was a difference between:
import App from './app'
and
import App from './app/index.js'
(the latter fixed the issue). Took me hours to catch this weird, hard to notice nuance :(
Another possible solution, that worked for me:
Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the #types/react-router-redux returned 5.x. So there were undefined variables used.
Forcing NPM/Yarn to use 5.x solved it for me.
In my case, the import was happening implicitly due to a library.
I managed to fix it by changing
export class Foo
to
export default class Foo.
I ran into this error when I had a .jsx and .scss file in the same directory with the same root name.
So, for example, if you have Component.jsx and Component.scss in the same folder and you try to do this:
import Component from ./Component
Webpack apparently gets confused and, at least in my case, tries to import the scss file when I really want the .jsx file.
I was able to fix it by renaming the .scss file and avoiding the ambiguity. I could have also explicitly imported Component.jsx
In my case I was using the default export, but not exporting a function or React.Component, but just a JSX element, i.e.
Error:
export default (<div>Hello World!</div>)
Works :
export default () => (<div>Hello World!</div>)
I got this error in react routing, problem was that I was using
<Route path="/" component={<Home/>} exact />
but it was wrong route requires component as a class/function so I changed it to
<Route path="/" component={Home} exact />
and it worked. (Just avoid the braces around the component)
And in my case I was just missing a semicolon at the import-decleration in one of my sub modules.
Fixed it by changing this:
import Splash from './Splash'
to this:
import Splash from './Splash';
In addition to import/export issues mentioned. I found using React.cloneElement() to add props to a child element and then rendering it gave me this same error.
I had to change:
render() {
const ChildWithProps = React.cloneElement(
this.props.children,
{ className: `${PREFIX}-anchor` }
);
return (
<div>
<ChildWithProps />
...
</div>
);
}
to:
render() {
...
return (
<div>
<ChildWithProps.type {...ChildWithProps.props} />
</div>
);
}
See the React.cloneElement() docs for more info.
I was getting this error also. The error was being caused by trying to export a component like this...
export default Component();
Instead of like this...
export default Component;
My understanding is that by adding the "()" at the end of the component, I was actually calling the function instead of just referencing it.
I did not see this in the answers above, but may have missed it. I hope it helps someone and saves some time. It took me a long time to pinpoint the source of this error!
The problem can also be an alias used for a default export.
Change
import { Button as ButtonTest } from "../theme/components/Button";
to
import { default as ButtonTest } from "../theme/components/Button";
solved the issue for me.
I was the same problem because I did import incorrect library, so i checked the documentation from the library and the route was changed with the new versión, the solution was this:
import {Ionicons} from '#expo/vector-icons';
and I was writing the incorrect way:
import {Ionicons} from 'expo';
Just want to add a case to this question. I walked around this issue by swapping the order of import, for example in my mixed of imports before:
import { Label } from 'components/forms/label';
import Loader from 'components/loader/loader';
...
import Select from 'components/select/select'; // <----- the error happen
After the change:
import Select from 'components/select/select'; // <----- Fixed
import { Label } from 'components/forms/label';
import Loader from 'components/loader/loader';
...
For me it was that my styled-components were defined after my functional component definition. It was only happening in staging and not locally for me. Once I moved my styled-components above my component definition the error went away.
It means some of your imported Components are wrongly declared or nonexistent
I had a similar issue, I did
import { Image } from './Shared'
but When I looked into the Shared file I didn't have an 'Image' component rather an 'ItemImage' Component
import { ItemImage } from './Shared';
This happens when you copy code from other projects ;)
I had an issue with React.Fragment, because the version of my react was < 16.2, so I got rid of it.
I was getting this issue too. My imports look fine, I could copy the contents of my copy and paste it where it was being used and that worked. But it was the reference to the component that was going wrong.
For me I just had to shut down expo and restart it.
Error? its definitely an import or export issue , you are reffering to a component or container that either you haven't exported from its defining script or when importing it u have used the wrong format.
Solution?
Go through all your component/container definitions and make sure you have exported them at the end of the script i.e "export default 'yourcomponentname';" or at the beginning of the component definition i.e
export const 'yourcomponentname'=() =>{
.......
}
At your import statements make sure you have not mixed up named and default imports based on your corresponding export statements

Categories