Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require underscore in react-native

The change log of react-native mentions https://facebook.github.io/react/blog/2015/04/17/react-native-v0.4.html

NPM modules compatibility: There are a lot of libraries on NPM that do not depend on node/browser internals that would be really useful in React Native, such as superagent, underscore, ...

But It doesn't work for me. It is how I install, through package.json

# package.json   "dependencies": {    "react-native": "*",    "underscore": "^1.8.3"    ... 

And I indeed see it in the npm dependecy

# npm ls ├─┬ [email protected] |  ... ├── [email protected] └── [email protected] 

And it does work for some other react components

It is how I require

var _ = require('underscore'); 

But it doesn't work, _ is undefined

like image 670
Ilake Chang Avatar asked Aug 25 '15 12:08

Ilake Chang


People also ask

What is underscore NPM?

Underscore. js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: https://underscorejs.org.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


2 Answers

If you are using ES6 module (like in ReactNative) the correct way is to use the import statement:

import _ from 'lodash'  let text = _.isUndefined(route.rightButtonText) ? 'Default value' : route.rightButtonText; 
like image 198
Hubert Perron Avatar answered Oct 02 '22 23:10

Hubert Perron


I am using lodash (underscore with more stuff) like this:

  1. Add this to the package.json "lodash": "^3.10.0"

  2. In the component you need just write: var _ = require('lodash')

And you are set.

Here is more info on lodash if you need lodash

like image 20
eyal83 Avatar answered Oct 02 '22 21:10

eyal83