Sydney Loteria Sydney Loteria - 11 months ago 60
React JSX Question

Variable is undefine - React JS

I have this global variable for config values that I require in index.js

import React from 'react';
import ReactDOM from 'react-dom';

// Config
const Dir = require('./Config/dir.jsx');

// Components
import Header from './Components/Header.jsx';

ReactDOM.render(<Header />, document.getElementById('app'));

this is the content of my dir.jsx

module.exports = {
css: 'public/css/',
js: 'public/js/',
img: 'public/img/'

When I accesssed the config variable in my header.jsx components using { Dir.css } it gives me an error "Dir is not defined".

Here's the header.jsx:

import React from 'react';


class Header extends React.Component {
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<a className="navbar-brand" href="#">{ Dir.img }</a>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav">
<li className="active"><a href="#">Link <span className="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li>
<ul className="nav navbar-nav navbar-right">
<li><a href="#">Link</a></li>

export default Header;

Here's the screenshot:

enter image description here

Answer Source

I presume you're using webpack to build your project

webpack won't import files unless there're used. In your case, you're just importing Dir and not using anywhere. webpack will skip this import for obvious reason.

There are 2 things you can do:

  1. Import Dir inside the Header component
  2. Pass the Dir as a prop to the Header component. Like this <Header dir={Dir} />. This can be accessed by this.props.dir inside the Header component.

I'll prefer the 1st way of doing.

P.S. You shouldn't use import and require together.