user8758206
user8758206

Reputation: 2191

React.js - Cannot import simple variable from one file into another

I can't figure out how to import a extremely simple variable from one file into another (new to react). I have the main App.js where line 3 appears to be the problem:

import React, {Component} from "react";
import NavMenu from "./components/nav-menu";
import navLinks from "/components/nav-links";

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      navLinks: navLinks
    }
  }

  render() {
    return (
      <div id="container">
        <NavMenu navLinks={this.state.navLinks} />
      </div>
    );
  } 
}

Which just imports (or should import) the navLinks variable from this nav-links.js file:

import React from 'react';

export const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

Can someone point me in the right direction of where I'm going wrong here? Also, it's being used to just render a navigation menu (so links within a tags) - is this generally the right way to go about adding nav links?

Stackblitz: https://stackblitz.com/edit/react-j42gep

Upvotes: 0

Views: 967

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You're missing to export the nav links as default :

import React from 'react';

 const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

  export default navLinks;

and add dot . in import navLinks from "./components/nav-links";

Upvotes: 1

Shubham Verma
Shubham Verma

Reputation: 5054

If you are doing this:

export const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

then you are importing it wrong. Then do this:

import {navLinks} from "./components/nav-links";

Note this: ./components/nav-links you forgot ./ in import statement

If you dont want to use {} the add default statement in your export like this:

const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

  export default navLinks;

Upvotes: 1

Related Questions