In React + Django app, JS renders properly when TS doesn't - javascript

I know JS and React, but have zero experience with TS.
I'm following a tutorial on YT, but figured I'd use TS to learn it, instead of JS.
And so after some setting up, I figured I'm ready to continue with the tutorial. However...
This works with JS:
index.html (Django template):
[irrelevant html setup]
<body>
<div id="main">
<div id="app"></div>
</div>
<script src="{% static "frontend/main.js" %}"></script>
</body>
App.js:
import React from "react";
import { render } from "react-dom";
const App = () => {
return <h1>Testing React code</h1>;
};
export default App;
const appDiv = document.getElementById("app");
render(<App />, appDiv);
index.js:
import App from "./components/App";
// that's it. The import is all there is in index.js
This is later compiled by babel-loader to main.js, which I'll not paste here, since it unreadable anyway. However, it does render the text from App.js.
When I have the analogical setup with TS, it doesn't work for some reason.
App.tsx:
import React, { FC } from "react";
import { render } from "react-dom";
const App: FC = () => {
return <h1>Testing React code</h1>;
};
export default App;
const appDiv = document.getElementById("app");
render(<App />, appDiv);
index.ts is the same as index.js, html file also remains unchanged.
I run tsc compiler, then run dev script that uses babel-loader. File main.js is created, but it has a one long line, and nothing is rendered when I run server.
Files App.js and index.js are created during compilation, but index.js has just export {} in it.
I suppose this is due to a difference in how TS and JS work, but I'm not sure what to even look for. I get no error messages.

Related

Why does a dynamic import only work in a page component (Next.js)

I'm new to Next.js. Currently I'm building up a site that used the Jarallax library. This library has to be dynamically imported like so
import Head from "next/head";
import dynamic from "next/dynamic";
const Jarallax = dynamic(() => import("../components/Jarallax"), {
ssr: false,
});
import JarallaxImage from "../components/JarallaxImage";
export default function Index() {
return (
<>
<Head>
<title>Next.js Example</title>
</Head>
<div className="section">
<h1>Next.js Example</h1>
</div>
<Jarallax speed={0.2}>
<JarallaxImage
src="https://jarallax.nkdev.info/images/image1.jpg"
alt=""
/>
</Jarallax>
<Jarallax speed={0.2} videoSrc="https://youtu.be/mru3Q5m4lkY"></Jarallax>
<div className="section"></div>
</>
);
}
This works perfectly when in the index.js file, in the /pages directory. However, I would like to use the Jarallax library in a component (located outside of the /pages directory). For some reason it no longer works. For example, if I make a component (outside of the /pages dir) with the same code as above, then try to dynamically import that component into a page...it doesn't work.
Is there something obvious about dynamic imports in Next.js that I am missing. Do they only work for components in the /pages dir?
Try to create separate index.ts file in components/Jarallax folder (the same folder as your component) and export default dynamic import
index.ts
import dynamic from "next/dynamic";
export default dynamic(() => import("./Jarallax"), { ssr: false });
and then use simple import where you need this component
import Jarallax from "../components/Jarallax";

Can someone the differences between these two Express-React-Node application?

I'm building an Express-React-Node app that I want to deploy on Google App Engine.
As I'm following several tutorials I've encountered these two apps architecture:
https://github.com/BalasubramaniM/react-nodejs-passport-app/tree/master/src
and
https://hackernoon.com/m-e-r-n-stack-application-using-passport-for-authentication-920b1140a134
I'd like to understand the differences.
The first one is only one app with Webpackand Babel.
On the client-side, I have a App.jsx file and Index.html file.
This is the App.jsx file:
import React from 'react';
const App = () => (
<div className='app'>This is a React app</div>
);
export default App;
And this is the html file:
<!DOCTYPE html>
<html>
<head>
<title>A Web App</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="./bundle.js"></script>
</head>
<body>
<div id="app">This is an Express App</div>
<script>
ReactDOM.render(
React.createElement(App.default),
document.getElementById('app')
);
</script>
</body>
</html>
The second one comes with a client app and a server app.
There is a index.jss file with the following code :
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import { Route, Switch } from "react-router-dom";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/" component={App} />
</Switch>
</BrowserRouter>,
document.getElementById("root")
);
registerServiceWorker();
and a App.js file with the following code:
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import queryString from "query-string";
class App extends Component {
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
this.props.history.push("/");
}
}
render() {
return (
<div className="App">
//some stuff here
</div>
);
}
}
export default App;
There is nothing related to react in the html file.
I kind of understand that with the first project the rendering part is mixed within the html file but I'm not really able to understand the differences and does things articulate in one app and the other.
The 2nd one appears to be using the create-react-app engine to generate the scaffolding and starter files. The 2nd example incorporates JWT user authentication that gets stored in local storage whereas the first does not appear to do so. Additionally, the 2nd example leverages React Router which allows you to build a single-page web application with navigation without the page refreshing as the user navigates. React Router uses component structure to call components, which display the appropriate information and allows you to add routes rapidly to build out the navigation. That is how the App component is being rendered within the imported Route component prop in index.jss. And if someone adds another Route with another path containing another component prop like this:
<Route path="/another-path" component={SubComponent} />
you could then access that component by traveling to baseURL/another-path
Token authentication and the use of React-Router are the primary differences between these two projects.
There are no differences. Both versions will call ReactDOM.render with an App element.
If you compile the second version using webpack, webpack will bundle all files together and will produce the same code as your first, partly manual solution.

Module not found in React

I am new to React. I have create new react app using following command.
create-react-app app-name --scripts-version custom-react-scripts-version
Inside src folder of that app i have created 2 new folders say Grid and Title and created files Grid.js and Title.js in respected folder.
Grid.js
import React from 'React';
export default class Grid extends React.Component {
render() {
return (
<div>
<h1>Grid</h1>
</div>
);
}
}
Title.js
import React from 'React';
const Title = () => {
return (
<div>
<h1>Title</h1>
</div>
);
}
export default Title;
Now, i try to import both into App.js file it won't.
import Title from './Title/Title';
import Grid from './Grid/Grid';
It shows following error.
Failed to compile.
./src/Grid/Grid.js
Module not found: D:\ReactAppCSS\node_modules\React\index.js does not match the corresponding path on disk react.
Same for Title.js.
Any help would greatly appreciated.
import React from 'react'
react is the package name!

import all variables from a file.js with an " import './file.js' " summoning

I'm working with the import function, I wish use an import like for css, I mean "import './file.css'" then all the css attributes are diffused in the file. I have tried the same with ReactJS but it fails.
My expectation is to imitate the css import for js files, but it doesn't work.
Here my sandbox
Here is the relevant code:
import React from "react";
import ReactDOM from "react-dom";
impoprt sample from "./sample"
import "./exported.js";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{sample[2]}
{text1}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I'm getting the error at the line when no using the star's import:
{text1}
I'm wondering how make something similar. Any hint would be great,
thanks
The offending code in your sandbox is: import "./exported.js";
One source of confusion is that you are using Create React App, which hides away the webpack magic which allows you to import your CSS files as import "./styles.css";.
This is not how module exports and imports work. I would recommend reading the section on exporting and importing details on exploringjs.com
What you are doing is essentially an empty import, i.e. you are not importing anything, just executing the file.
Empty import: only loads the module, doesn’t import anything. The
first such import in a program executes the body of the module.
import 'src/my_lib';
But here are various ways to import something in a nutshell.
Assumption: your ./exported.js file has the following exports:
// some other code
export { text1, text2 };
export default config;
Then you can import them in various formats
// import only the default export
import config from './exported.js';
// This only imports the export qualified with default, it ignores others
// i.e.
console.log(config); //works
console.log(text1); // fails
console.log(text2); // fails
// import everything the module exports, but as a namespace
import * as myLib from './exported.js';
// usage: all named exports are properties of the myLib object
console.log(myLib.text1); // works
console.log(myLib.text2); // works
console.log(myLib.config); // should not work, unless you have also exported config as a named export
// import only what you need
import { text1, text2 } from './exported.js';
console.log(text1); // works
console.log(text2); // works
// you can also rename them
import { default as x, text1 as a, text2 as b } from './exported.js';
console.log(x); // works --> config
console.log(a); // works --> text1
console.log(b); // works --> text2
You need to do import defaultExport from 'moduleName'; so you can use defaultExport in your code.
Doing import 'moduleName'; will only run the code in the module but not import anything (see MDN for more info)
In your sandbox, doing import sample from 'sample.js'; would do it.
The problem in your code cause a breaking a import, that didn't let include your css file, the problem is importing export.js and sample.js it must include using a correct Destructuring, e.g.:
import React from "react";
import ReactDOM from "react-dom";
import { text1, text2 } from "./exported.js";
import sample from "./sample.js";
import "./styles.css";
Here complete sample Code Sample.
More info about import statement: import
Destructuring assignment statement: destructuring assignment .
Best regards.

ReactDOM.render() unresolved

import React from 'react';
// import ReactDOM from 'react-dom';
import ReactDOM from 'react-dom/dist/react-dom.min';
import {Alert} from 'reactstrap';
class AlertLine extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
}
onDismiss = () => {
this.setState(
{
visible: false
}
);
};
render() {
return (
<div>
<Alert color="success" isOpen={this.state.visible} toggle={this.onDismiss}>
<strong>Success!</strong> You successfully read this important alert message.
</Alert>
</div>
);
}
}
ReactDOM.render(
<AlertLine/>,
document.getElementById('root')
);
ReactDOM.render() works just fine with 'react-dom' for development. However, as soon as I try import minified 'react-dom.min' instead of 'react-dom', render() goes unresolved and nothing happens. I can't find render() from content assist(ctrl + space) neither.
I've installed react#15.6.1 and react-dom#15.6.1 with npm and they're on 'npm list'. Then I tried reinstall them but that didn't work.
In your case, you have to use import ReactDOM from 'react-dom' because import doesn't mean "file import", it means "ES6 module import".
To minify your bundle file, try uglifyjs-webpack-plugin (if you're using webpack) or minifyify (if you're using browserify)
Non-module
Node modules loaded with require / import must populate an exports object with
everything that the module wants to make public.
stackoverflow.com/a/14914442/6836839
react-dom.min.js is used as a simple js library, you can't import / require
Install
Since you can't require / import, you need to load it as a normal js script:
<!-- index.html -->
<script src="node_modules/react-dom/dist/react-dom.min.js"></script>
Use
// Just call it...
ReactDOM.render(component, document.getElementById('root'))
Note
If you load React from a tag, these top-level APIs are available on the ReactDOM global.
If you use ES6 with npm, you can write import:
import ReactDOM from 'react-dom'
If you use ES5 with npm, you can write:
var ReactDOM = require('react-dom');
https://facebook.github.io/react/docs/react-dom.html
Import name is not same as the component name which you are exporting.
When you Import a component in a common Index.js file and you are Importing a component(import Header from './components/Header';).
Header should be different from export default headerComponent; name

Categories