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
Related
I have created a sample test app as below
import React from 'react';
class App extends React.Component {
render() {
const SampleBtn = (props) => {
console.log('button rendered');
return <button>test</button>;
};
return (
<div className="App">
<SampleBtn />
</div>
);
}
}
export default App;
When I run the above app, console.log('Button rendered') is called twice. I tried to remove <React.StrictMode> also, it is called twice and sometimes it multiplies. How to resolve this and can I know the reason behind this?
I have used HTML button and create a stackblitz code as below, even then I am seeing the logging twice. Please see the url below
https://react-xd9pzh.stackblitz.io
Maybe add a render method to the class and move the CustomButton outside the class, a working code will help you to find the issue.
Edit: first code example was unclear to me, like others said, probably it's StrictMode. Keep in mind that it will run only in the development environment. For a quick check on your local machine, for example, if you're using create-react-app you can simply run the build command and then serve the app in your browser to verify if you get a double console.log with the prod build.
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>)}
}
I upgraded my React to 16.3.2 and used React.createRef() as seen here: https://reactjs.org/docs/react-api.html#reactcreateref
But when I am getting the following error:
Uncaught Error: Expected ref to be a function or a string.
When I look at what the function React.createRef() actually returns, I see this:
{ current: null }
What is going wrong here? Has the implementation changed?
I am using react-router-dom for routing, and my component is a class component.
EDIT: this is my code:
export class MyComponent extends Component {
constructor(props) {
super(props);
this.cardRef = React.createRef();
}
render() {
return (
<div>
...
<Card ref={this.cardRef}>
...
</Card>
</div>
);
}
}
To address this:
What is going wrong here? Has the implementation changed?
Nope. It just returns an Object with a property current being set to null. No magic here. You just initiate property in a component with such object and then you pass a reference of this object to the component. React then at some point reassigns current.
this.component = React.createRef() // this.component = { current: null }
// we pass a reference to object above and react will mutate current property at some point
<div ref={this.component} />
The error message seems to suggest you are still using an older version of react. What I would suggest is to
make sure you got the latest versions of both react and react-dom (16.3.2) declared in package.json
then removed node_modules and install it again
I had an issue with my defaultProps. Since we cannot use useRef hook in defaultProps; this is what worked for me:
MyComponent.defaultProps = {
formRef: React.createRef()
}
Good Luck...
If I have an ES6 component like so:
component OldThing extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.someProp}</div>;
}
}
an ES6 container like so:
const OldThingContainer = connect(mapStateToProps, mapDispatchToProps)(OldThing);
and a new typescript component like so:
component NewThing extends React.Component<Props, State> {
render() {
return <OldThingContainer someProp={someValue} />
}
}
I currently get an IntrinsicAttributes error about someProp not existing on OldThing. How do I get rid of that error without adding types/typedefs to/for OldThing and/or OldThingContainer? I tried the #augments solution on the OldThingContainer where it's defined but that doesn't seem to help. Neither did adding the comment on the component itself.
The reason I want to be able to import JS without types is that we are adding typescript to a very large, multiple years old code base and it's currently difficult to get people to write typescript components at all, let alone if they also have to type out every existing component their component wants to import.
Is there an existing elegant solution to this problem or am I going to have to go through ahead of everyone and manually type every existing JS component (hundreds) in some typedef file to get rid of/prevent these errors?
I tried your example and it seemed some issue with the type connect inferred for your component.
One quick'n'dirty fix would be to annotate your JS component with:
/**
* #type {React.ComponentType<any>}
*/
const OldThingContainer = connect(mapStateToProps, mapDispatchToProps)(
OldThing
);
One more elegant fix (but maybe not possible) would be trying to dive into the react-redux typings. The connect function requires you to supply some type arguments for it to properly work. When not supplied, those arguments are given {}, not any (because any can silently eat your types).
Comment: From the few I've worked with react+redux+typescript, lib typedefs are one of the biggest pain points. React typedefs can get really complicated. (flow just will hang up your editor with "waiting for flow server", which is even worse). As TS+Redux gets more popular and more support is added, this may get a lot better in a few months...
I’m trying to use clipboard.js in a React component, and it causes my devserver to start failing with the Node error:
ReferenceError: Element is not defined
at Object.<anonymous> (/mnt/home/me/code/board/webapp/node_modules/matches-selector/index.js:6:13)
I initialize the clipboard in componentDidMount but am still getting this error. I actually think the error may have something to do with my import, because even when I don’t actually initialize the clipboard (but include the import) I get the error. Does anyone have an idea what I might be doing wrong?
Relevant code (styling excluded):
import React, { Component } from 'react';
import Clipboard from 'clipboard';
export default class CodeSnippet extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
new Clipboard('.copyButton', {
target: () => document.getElementById('snippet')
});
}
render() {
return (
<div style={styles.snippetCopy}>
<div id="snippet" style={styles.snippet}>
{'this text will copy'}
</div>
<button
className={"copyButton"}
id="clipper"
data-clipboard-text='snippet'
style={styles.buttonStyle}
text={'Copy code'}>
</button>
</div>
);
}
}
You can't require clipboard.js if you're doing server side rendering. It's annoying but instead of installing via npm, they suggest including the script manually like this:
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
https://github.com/zenorocha/clipboard.js/issues/157
I created a fiddle updating your code. It's a suggestion of integrating clipboardjs and React, using ref's and clipboardjs' text function.
Check here: https://jsfiddle.net/mrlew/L54ky6hj/