Jomoos Jomoos - 2 months ago 7
React JSX Question

Can't find variable React - Even though it is not used in file

I am getting a "Can't find variable: React" error in my react native project. But, what baffles me is that I am not at all using

React
in that file, although, I am importing a custom component which uses it though. Here is a MCVE of my problem.

First up
construction.js
:

import React from 'react';
import { View, Text } from 'react-native';

class UnderConstruction extends React.Component {
render() {
return (
<View>
<Text style={{ padding: 75 }}>
This page is under construction :(
</Text>
</View>
);
}
}

export default UnderConstruction;


Next up,
render.js
:

import UnderConstruction from './construction';

export function render() {
return (
<UnderConstruction />
);
}


And lastly,
index.ios.js
:

import React from 'react';
import { AppRegistry } from 'react-native';
import * as Factory from './render';

class Demo extends React.Component {
render() {
return Factory.render();
}
}

AppRegistry.registerComponent('Demo', () => Demo);





Running this app will cause the error
Can't find variable: React
on
render.js
line number
5
, which is:

<UnderConstruction />


I found out the problem can be solved by just adding an
import
statement for
React
on
render.js
like:

import React from 'react';
import UnderConstruction from './construction';

...


I am curious as to why should I
import
React
even though I am not using it in
render.js
, hence this question. So, what causes
Can't find variable: React
error in my
render.js
file?

Answer

To use render function you need to import React in your file because react creates your elements. I would suggest you go through your transpiled Javascript file once, you will understand what I mean.

I was myself facing this issue sometime back and when I saw the transpiled JS file and I then I saw how it works.

So in your transpiled file it would be something similar to this:-

(0, _reactDom.render)(_react2.default.createElement(_Root2.default, { store: store, history: history }), document.getElementById('app'));
Comments