Errors with clipboard.js in React component? - javascript

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/

Related

Dynamic component used in render is getting called twice

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.

‘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

How to make react-datepicker display properly?

I cannot make the component react-datepicker display properly.
it actually displays like this.
I wish it could display at least like the documentation for the component does.
I first thought it was a dependency problem, and added all the dependencies the doc says are needed. The result is still the same.
Some stackoverflow questions talked about this and referred to a missing stylesheet. However I imported everything with npm, so that shouldn't be the problem.
My class component looks like this :
import React from "react";
import "./style.css";
import DatePicker from "react-datepicker";
class Filters extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate : new Date()
};
this.handleStartChange = this.handleStartChange.bind(this);
}
handleStartChange = (date) => {
this.setState({
startDate : date
})
}
render() {
return (
<div className="filters">
<div id="filterbox">
<p id="titre">Filtres</p>
<DatePicker
selected={this.state.startDate}
onChange={this.handleStartChange} />
</div>
</div>
)
}
}
export default Filters;
I apologize in advance if the problem is very obvious, I'm quite new to reactjs.
You forgot to import the package css.
From the documentation:
import "react-datepicker/dist/react-datepicker.css";
I think you have to import the react-datepicker.css too, not only the package itself.
import "react-datepicker/dist/react-datepicker.css";
Below is a simple example of how to use the Datepicker in a React
view. You will also need to require the CSS file from this package (or
provide your own). The example below shows how to include the CSS from
this package if your build system supports requiring CSS files
(Webpack is one that does).
you haven't imported their css file.
import "react-datepicker/dist/react-datepicker.css";

How to integrate external scripts to react such as PayPal Smart Check out?

So I'm trying to add paypal smart checkout to a react app and I seem to not be able to do it. The problem seems the script does load for the fist couple of seconds then immediately trows error saying the script does not exist when a second ago it was there
I have tried what a guy on youtube suggested for loading third party libraries but to no avail. I get that problem, I tried several other ways suggested but really this is the best approach and it still fails
App.js------------------------
import React, {Component}from 'react';
import './App.css';
import Paypp from './pyapalload'
class App extends Component {
constructor (props){
super(props);
this.state={
hotelname:'',
}
}
render() {
//console.log(this.props)
return (
<div>
Hl
<Paypp/>
</div>
);
}
}
export default App;
second js file
import React, { Component } from 'react';
class paypalload extends Component {
constructor(props){
super(props);
this.state={
}
}
shouldComponentUpdate(){
return false;
}
componentDidMount(){
this.paypa=new paypal.Buttons().render('#paypal-button-container');
}
render(){
//console.log(paypal);
return(
<div>
Test
<div id="paypal-button-container" ></div>
</div>
)
}
}
export default paypalload;
And the script is loaded from the public/index.html
If anyone could help that would be much appreciated.
None of the JS provided by PayPal to render smart payment buttons is intended to be run server-side. It is all client-side code, so your App should merely serve it to the browser, to be executed there.
You can get it working in a .html file first if this simplifies your development, conceptually, and then determine how to best have your node app serve up that client-side HTML/JS

Importing jQuery, Masonry & other libraries in GatsbyJS

Even after googling, I'm having trouble finding the best way to import/include jQuery, Masonry and some other jQuery based libraries in my GatsbyJS project using the webpack pipeline.
I can include tags manually, but my understanding is that it's ideal to use import so it gets pipelined and packed.
import jQuery from '../js/jquery.min.js'
import '../js/flickr.js'
import '../js/flexslider.min.js'
import '../js/lightbox.min.js'
import '../js/masonry.min.js'
This always produces the error:
ReferenceError: jQuery is not defined
from the flickr.js & masonry..min.js libraries
You should have a look on the excellent ReactJS doc on How to integrate React with other libraries.
The idea is to attach a ref to an empty <div /> and reference to it in componentDidMount()where you can pass it to your jQuery plugin.
code from the react's doc:
class SomePlugin extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.somePlugin();
}
componentWillUnmount() {
this.$el.somePlugin('destroy');
}
render() {
return <div ref={el => this.el = el} />;
}
}

Categories