Search code examples
javascriptreactjsfractionsmath.js

Can't display fractions in React project. Child error instead even with mathjs


I want to create my own recipe converter and needed partial quantities of measurements like cups and teaspoons in fractions. When I attempted to insert these as portions into an object as shown below, it displays a decimal on the webpage instead of a ratio as desired.

export const ingredients = [
{
    id: 1,
    name: 'rice wine vinegar (or sub apple cider vinegar)',
    category: 'Pickled Vegetables',
    portion: 2/3,
    unit: 'cup',
},

After research, I have discovered the npm module mathjs and downloaded it in an attempt resolve my issue.

However after adding this code, (which appears to work on its own)

const math = require('mathjs')

math.config({
     number: 'Fraction'
})

And then this code

export const ingredients = [
{
    id: 1,
    name: 'rice wine vinegar (or sub apple cider vinegar)',
    category: 'Pickled Vegetables',

//portion value has changed
    portion: math.fraction(`2/3`),
    unit: 'cup',
},

Which I had copied from the Fraction example from the module's website I have received the error that this Object is not a valid React child and to use an array instead.

Based off of what I had seen from the website, it seemed as though not having this value in an array was perfectly fine.

I also tried placing the / in '' but it was not accepted by VS Code

portion: 2'/'3,

The text editor explained that this was incorrect syntax and now I am at a loss.

What is wrong with my code and am I on the right track to working with fractions?


Solution

  • It's because you're only doing half the formatting...

    Try this:

    /* for readability let's declare two thirds first */
    const twoThirds = math.format(math.fraction('2/3'), { fraction: 'ratio' })
    
    export const ingredients = [
    {
        id: 1,
        name: 'rice wine vinegar (or sub apple cider vinegar)',
        category: 'Pickled Vegetables',
    
    //portion value has changed
        portion: twoThirds,
        unit: 'cup',
    },
    

    The MathJs example page shows all fraction options