Reactjs not understanding ES6? - javascript

I'm reeeally new to reactjs and I was copying a tutorial (link: https://www.youtube.com/watch?v=Ke90Tje7VS0). I'm currently on Windows and did the following on cmd (as per tutorial):
npm i -g create-react-app#1.5.2
create-react-app
The files/directories, etc. have all been installed, but I noticed that my App.js features this syntax:
function App()
{
return(...);
}
While the App.js from the tutorial (and many other demos) use this kind of syntax, from what I understand it's ES6:
class App extends Component
{
render()
{
return(...);
}
}
I tried copying this syntax onto my App.js but then my react app (from typing npm start in cmd) broke. How can I fix this (i.e. use the ES6 code without breaking my project)? Does it have the exact same functionality as my above code anyway?
Here is my error message:
Line 8: Parsing error: Unexpected token
6 | class App extends Component {
7 | return (
> 8 | <div className="App">
| ^
9 | <header className="App-header">
10 | <img src={logo} className="App-logo" alt="logo" />
11 | <p>
I really doubt it's a parsing error, the JSX worked fine with function App(), but when I changed it to class App extends Component without touching anything else, the program broke.

The issue here is from trying to return HTML/JSX from your class directly, rather than from within a function. If you're using a class, you'll need to wrap the returned HTML/JSX in the render function.
For example:
class App extends Component {
render() {
return (...)
}
}
Also, regarding the difference between the two syntax examples you posted: the first is what's called a functional component, while the second is a class-based component. In the past, class-based components were used for anything that required state (data held and manipulated internally) or life-cycle methods, while functional components were used for components that were presentation-only. With Hooks (introduced , functional components can now have state and access to life-cycle methods so the two are pretty much equivalent. Put simply, you can think of a functional-component as just the render method of a class-based component.
In general the difference in use goes like this:
Class-based:
class App extends Component {
render() {
return (...)
}
}
Functional:
const App = props => { // or function App(props) {
return (...)
}
Check out these docs for a bit more detail:
Class-based components: https://reactjs.org/docs/react-component.html
Discussion on functional components: https://reactjs.org/docs/components-and-props.html

-By assuming you are begginer in React you need to install react in your machine with this command below
npm i -g create-react-app#1.5.2
Then to create a new react app type command npx create-react-app yourAppName
And you question was does React understand ES6 and answer is big
YES
When you successfully installed and handle your app, now it's time to see how es6 works perfectly with React
Instance:
// importing react library
import React from 'react';
// ES6 Function
const App = () => {
const data = [
{
firstname: 'Joe'
},
{
firstname: 'Claire'
},
{
firstname: 'John'
}
]
return {data.map(data => <li key={data.firstname}>{data.firstname}</li>)}
}

Related

‘state’ is not defined no-undef

I use a tutorial to learn React and I got stuck pretty quickly.
In the tutorial they use this code:
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0,
};
render() {
return (
<React.Fragment>
<span>{this.state.count}</span>
<button>Increment</button>
</React.Fragment>
);
}
}
export default Counter;
And everything works great.
But in my case, I get this error:
src\components\counter.jsx Line 4:3: ‘state’ is not defined no-undef
Search for the keywords to learn more about each error.
After trying everything, I think it's because of the react version (They use an older version).
So my question is how to fix this error, And what has actually changed between the versions that prevents my code from working. Tnx!
This is an issue not related to react itself but projects created using create-react-app I believe. The ongoing issue is discussed in comments and it has worked for some people by simply re-using the command itself to create a new project but still a comment by maintainers is awaited. So it's not something you did wrong. Chill.
I have been tracking this since yesterday and even tweeted about the same. Some dependency might have been messed up. Probably eslint or one of babel plugins.
The link to the issue - https://github.com/facebook/create-react-app/issues/10598
I ran into the same problem. I was using the wrong version. The documentation below provided me instructions to create a new react app, for the new version. Now I fixed the issue.
https://create-react-app.dev/docs/getting-started/
Put state in constructor:
constructor(props) {
super(props);
this.state = {
count: 0,
}
Since Constructor is not initialized, the state you are assigning a keyword in React, which is why it's coming as an error.
Fix for your code like this by adding constructor -
constructor(props) {
super(props);
this.state = { count: 0 };
}
For more information, refer -
Counstructor in React Class Component

too much render with react markdown

I am using React Markdown (https://www.npmjs.com/package/react-markdown) to render markdown content in my NextJS project.
When I refresh I have two "toto" & "titi" in my terminal... It is normal or what's wrong with this code?
import Head from 'next/head';
import ReactMarkdown from 'react-markdown';
function Section ({ data }) {
const content = JSON.parse(data.markdown);
const {
title,
sortContent
} = data;
console.log('toto');
return (
<>
<main>
<h1>{title}</h1>
<h1>{sortContent}</h1>
<ReactMarkdown source={content.default} escapeHtml={false} />
</main>
</>
)
}
export async function getServerSideProps (context) {
const json = await import('../../content/article1/data.json');
const content = await import('../../content/fr/article1/content.md');
console.log('titi');
return {
props: {
data: {
title: json.title_content,
sortContent: json.short_content,
markdown: JSON.stringify(content)
}
}
}
}
export default Section
It's part of Reacts development tooling, StrictMode. It is expected and only applies in development mode. You can remove the StrictMode to see it only render the expected number of times, but obviously you lose some development tooling. This tooling can warn you about certain unsafe or unwise practices you might want to avoid such as using legacy APIs.
More details here:
Reactjs Docs
A blog with a good overview
If this is truly the only code you have, then it looks like it's normal. You may have other code that uses these components and that's why in shows twice. But based off the code you have right there, there's no bug.
This is a known side-effect of using React.StrictMode, only in debug mode. You can read more about this here.
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer

Material UI styles not working in component (warning: several instances of `#material-ui/styles`)

I've created a stand-alone React component that uses the Material UI (4.8.3) library and published this to a private NPM package in order that it can be used in a range of apps.
The stand-alone component project works fine (I'm using Storybook to test the component), but when I publish and then import the component into a new React project (created using create-react-app) I get the warning:
It looks like there are several instances of `#material-ui/styles` initialized in this application. This may cause theme propagation issues, broken class names, specificity issues, and makes your application bigger without a good reason.
The component renders on the page as seen below, but without any theming applied:
When it is clicked, any theming on the main React App is removed (note the dark blue bar in the background behind the menu has lost its color):
I'm using the Material UI withStyles functionality to theme my component, which I guess is the problem as my main React app is also using this, but this is the recommended way to apply to style. Does it feel like I need to somehow inherit an instance of the theme from the main host App?
My component project was created using create-react-library and so is using Rollup (0.64.1) and babel (6.26.3).
Here is the component:
import React, {Component} from 'react'
import { withStyles } from '#material-ui/core/styles'
const styles = theme => ({
root: {
fontSize: '14px',
}
})
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class MyComponent extends Component {
render() {
const { classes } = this.props
return (
<div className={classes.root}>Hello world</div>
)
}
}
export default withStyles(styles)(MyComponent)
Which is published to an NPM package and then imported into the main app using:
import React, { Component } from 'react'
import { MyComponent } from '#xxx/mycomponent'
const styles = theme => ({
root: {
display: "flex",
flexGrow: 1
}
});
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Class
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class App extends Component {
//
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
render() {
//
const { classes } = this.props;
return (
<div className={classes.root}>
<MyComponent />
</div>
);
}
}
export default withRouter(withStyles(styles)(App))
I had the same issue, but I do not use StoryBook. This is the first link in Google, so I post my case here, as it might help.
This is the link on how to fix the alert, but it does not work for me. npm dedupe does nothing and I am unable to change config since I am using create-react-app.
So I did following:
Removed #material-ui/styles dependency from package.json
Ran npm i
Changed all import styles from '#material-ui/styles' to import styles from '#material-ui/core/styles'
I have an almost identical setup and ran into this exact issue when importing the components into a different project. I should mention that we're using webpack to build the app that's consuming the component. It was suggested to me to try the following in my webpackconfig:
module.exports = {
...
resolve: {
alias: {
"#material-ui/styles": require.resolve("#material-ui/styles")
}
}
}
This worked great for my case.
For reference: https://webpack.js.org/configuration/resolve/
You should link #material-ui/styles in your story book
so first need to npm link #material-ui/styles in your story book and than in your apps
Please try to install the below package. This helped resolve my issue.
npm i #mui/material

What is the best way to create component library for both React and Preact?

I'm currently working on a project which involved both React and Preact. I came across to this where I need to use same component for React and Preact.
Is it a good idea to put the component into npm library package. What are the possible way to create component library for both React and Preact? Looking forward to hear your ideas and discussions.
The code might look like as the following:
React Project: Home.js
import React from 'react'
import Fancy from 'fancy-component/react' // My <Fancy /> component library
class Home extends React.Component {
render() {
return (
<div>
{/* Other parts of the code run here*/}
<Fancy text='🦄' />
</div>
)
}
}
export default Home
Preact Project: AnswerPage.js
import { h, Component } from 'preact'
import Fancy from 'fancy-component/preact' // My <Fancy /> component library
class AnswerPage extends Component {
render() {
return (
// Other Preact codes run here again
<Fancy text='🚀 again' />
)
}
}
export default AnswerPage
Component library: fancy-component
const Fancy = ({ text = '' }) => (
<div>
<span>{`This is so Fancy ✨ ${text}`}</span>
</div>
)
export default Fancy
We did this very thing recently, and because we could not find much information regarding this online it involved quite a bit of trial and error. This is what we ended up with:
Folder Structure:
/apps
/mobile
/desktop
/shared
/components
With preact 10, preact-compat is built in so you don't have to worry having separate components - just use React as normal for the components in your shared folder and preact will automatically alias the imports correctly.
As far as aliasing goes, we added this into our preact.config.js so that we can import the components like #components/Date from the app directory
config.resolve.alias['#components'] = path.resolve(__dirname, '../../shared/components')
For the React app, the only way that I could make that work was to add the aliasing in the babel.config.js like so:
['module-resolver', {
alias: {
'#components': '../../shared/components'
}
}]
I hope that this helps someone else that might be stuck on this!

Writing an open source component with hooks results in Invalid hook call when using it after transpilation

I'm writing a react component which I plan to open source.
For that I have this component inside a repository and transpile it with babel. I'm using hooks here.
A small excerpt of that component would be:
import React, { useRef } from "react";
const MyComponent = props => {
const index = useRef(0);
// ...
return (
<RenderStuff />
);
};
export default MyComponent;
I transpile it via babel with that .babelrc:
{
"presets": ["#babel/preset-react", "#babel/preset-env"]
}
When I try to use that Component inside an example create-react-app project I get an error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/warnings/invalid-hook-call-warning.html for tips about how to debug and fix this problem.
I checked it all, I have react and react-dom only as a peerDependency of my component and I only get one version when I run npm ls react react-dom inside the example project.
I'm pretty confident that the hooks inside the component aren't really the problem, before I had this component inside an example project and it worked there, the only difference is now that I have it inside an own project.
When I remove the everything and just write a function component which renders a headline hello world I can use it, so I think the reason are the hooks.
The transpiled code looks like this:
var MyComponent = function MyCompontn(_ref) {
var index = (0, _react.useRef)(0);
// ...
}
Could the error be there?
What are my options to fix this?

Categories