I'm trying to import mousetrap into a react project for some simple keyboard bindings. I installed Mousetrap via yarn. I don't have any errors importing, but the Mousetrap library object is undefined when I try to use it. This is from my main App.tsx component
import Mousetrap from 'Mousetrap';
export default class App extends React.Component {
componentDidMount() {
Mousetrap.bind(['left'], dataStore.pagination.prev());
Mousetrap.bind(['right'], dataStore.pagination.next());
}
componenentDidUnmount() {
Mousetrap.unbind('left', dataStore.pagination.prev());
Mousetrap.unbind(['right'], dataStore.pagination.next());
}
public render() {
Here's the error I'm getting.
error
I also tried initiating an Mousetrap object to use, but I get this error (plus there's nothing in the documentation saying I would need to).
const mousetrap: Mousetrap = new Mousetrap();
error
I'm using react, typescript, mobx, material-ui and several other libraries, and I'm quite new to all of them. Any advice would be helpful.
Mousetrap has no named export, so your named import statement will result in undefined. You can import the library using:
import * as Mousetrap from 'Mousetrap';
Related
I used npm init react-app appname which creates, among other files, App.js. In that file is a function component:
function App() {
return (
<SomeJSX />
);
}
I edited the function component into a class component, like so:
class App extends React.Component{
render() {
return (
<TheSameJSX />
);
}
}
Now, when I run npm start, I get an error:
Failed to compile
src/App.js
Line 4:19: 'React' is not defined no-undef
Search for the keywords to learn more about each error.
I imagine I need to add some setting somewhere that will automatically include React without me needing to explicitly import it at the top of every file. How do I do this? And why does this npm package not do that by default? I know a bit about javascript (and html and css), and have read a bit about React, but I am completely unaware of how npm or webpack works.
Thanks in advance!
EDIT: To clarify, I know how to import stuff with javascript. I can easily add import React from 'react'; to the file and make it work. However, I find it difficult to believe that adding an import statement to every single javascript file is the recommended method, and I don't understand why this example app wouldn't be set up so as to avoid having to do that. Am I mistaken? Do I really need to manually import the same thing over and over again within the same project? Could I set a global variable to React so that I can use it from wherever?
In your default function component you're not extending any classes and just writing a simple function
function App() {
return (
<SomeJSX />
);
}
In class component, you're in fact extending the Class Component by React.Component provided by React default export object and hence you must import it from the package
//only use one of these
import * as React from "react";
import {Component} from "react"; // you can directly extend without writing `React.` with this import
import React from "react"
So your code would be
import React from "react";
class App extends React.Component{
render() {
return (
<TheSameJSX />
);
}
}
Any of the above imports should be fine with a preference to the first and second one.
I'm trying to load translations from a JSON file with react-localize-redux and I keep getting this error. This is all fairly new to me so I apologise if it is something obvious. As fair as I can tell from reading documentation this "should" work?
The error message I am receiving:
translate.js
import { combineReducers, createStore } from 'redux'
import { localizeReducer, initialize, addTranslationForLanguage, getTranslate } from 'react-localize-redux'
import translationsEn from '../../../nls/en.json'
const localeStore = createStore(combineReducers({
locale: localizeReducer
}))
const languages = ['en']
localeStore.dispatch(initialize(languages))
localeStore.dispatch(addTranslationForLanguage(translationsEn, 'en'))
export default getTranslate(localeStore.getState().locale)
and in my component:
import translate from '../state/translate/translate'
...
<span className='node-output-schema__title'>{translate('outputSchema.title')}</span>
Any ideas to what might be going wrong?
it seems like you mixed some different frameworks inside here.
The localisation package is called - react-localize-redux.
But inside your error logs I can see that you are using some angular.
Also I just checked the documentation from the react-localize-redux package and it seems like you are working with an outdated version.
For me it should be enough to just provide a Provider to your app and afterwards use the higher order component (import { withLocalize } from "react-localize-redux";
)
Also I would recommend to use this package, which is a lot easier to handle (and indeed I used it for a project myselft)
react-18next (https://github.com/i18next/react-i18next)
this error rases because your property is undefined, so check your error and get the exact line(you can find the error on the console tab of your browser) and check which property used there and check where you filled that property if you didn't fill your property then set it
I am importing with the below statement
import React, { Component } from 'react';
and I want to use unmountComponentAtNode but keeps getting the error
Object doesn't support property or method 'unmountComponentAtNode'
React.unmountComponentAtNode(document.getElementById('root'));
I'm using an old version of the React library (15.4.1).
So how should I call unmountComponentAtNode so that I do not get an error:
unmountComponentAtNode is not exported by 'react'?
What should I import so that I do not get an error?
The big change in v15.4 was the separation of React and ReactDOM. unmountComponentAtNode() became a method of ReactDOM. Use:
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
What is the major benefit of writing
import React, { Component } from 'react';
class Link extends Component {
...
}
instead of
import React from 'react';
class Link extends React.Component {
...
}
when it comes to react 15.4.x??
In my perspective and in my case (correct me if I am wrong) it does not matter at all since:
I am using a webpack2 for making my bundles;
I use code splitting to split my app code from vendor code;
I use webpack.optimize.CommonsChunkPlugin plugin with minChunks: Infinity setting to make sure that all vendor code is included only once.
From understanding how ES6 imports work I understand that by using named import of {Component} I state that I want to use only Component component in my code, which looks.. cleaner.
But since whole React package is still used in the app, I can create my classes with extension from React.Component instead of just Component and in result webpack will still produce the same amount of code and my bundle size will be the same in both cases.
Am I correct?
There is no difference, React.Component is the same object as Component, the second way is more eloquent in my opinion, because it really explains that you are using the Component object from the React library.
The first one seems to refer a member,
but, it comes from the pre modules era of javascript, where everything had to be attached to the exported global namespace (just to avoid global namespace pollution).
something that could be under the hood:
// this should be assumed as an example only.
class React { ... }
class Component { ... }
React.Component = Component;
// ES6
export {Component}
export default React;
// ES5
window.React = React;
Note: as someone said, you also need to import React because JSX needs to have it on scope, but, if you want to avoid it, you can expose React globally (window.React = React)
This import statement:
import React, { Component } from 'react';
is really doing two things. It imports the default export, under the name React (which is just a convention, you could call it what you want). It also imports a named export, Component.
The reason that the default React is imported is actually to make JSX work. When your JSX code is transpiled, then it substitutes <div> for React.DOM.div(), so React must exist otherwise things break!
Importing both things separately means that your JSX works but you get to write Component instead of React.Component in your code.
When you do import anything from "react", then the whole file is going to get included either way - any attempt to reduce the bundle size (e.g. Dead Code Elimination, Tree Shaking) is an additional, separate step, which doesn't depend on your import statements but the parts of the code that you use.
In the case of this library, the sane thing happens: the child Component of the default export refers to the same thing as the named export Component.
However, bear in mind that this isn't guaranteed to be the case! If the React library code contained the following:
export default {
Component: "foo"
};
export const Component = "bar";
Then React.Component === "foo" and Component === "bar".
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/