node.jsreactjsreact-nativemathjs

Getting TypeError: undefined is not an object (evaluating '_mathjs.default.fraction'), React-Native


I get this error whenever I use 'mathjs'

TypeError: undefined is not an object (evaluating '_mathjs.default.fraction')

Basically my code is this

import React from 'react';
import {View, Button} from 'react-native';
import mathjs from 'mathjs';
const App = () => {
  return (
    <View>
      <Button
        title="TestButton"
        onPress={() => {
           console.log(mathjs.fraction(1, 2)); // equals to ½
         }}
        />
   </View>
  );
};

export default App;

Solution

  • Looking at the library's npm page, I think you need to use a named import, not the default one:

    import { fraction } from 'mathjs';
    

    Named exports won't show up as properties of the default export. You could use this syntax to get all the named exports:

    import * as mathjs from 'mathjs;
    

    Although unless you're actually using them all I don't recommend this, since I think it would defeat tree-shaking for your javascript bundle.

    See import docs for more information.