How do I correctly import React to javascript?

How do I correctly import React to javascript?
0.0 0

#1

Here is my github repository: https://github.com/UnschoolAcademy/Markup-Previewer-2
I did all the imports that FreeCodeCamp said to do at the start of my code, but it still doesn’t seem to be working. Am I doing something wrong besides the way I am importing it into my code?

Here is just my javascript code for convinience:

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider, connect } from 'react-redux'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

class TypesOfFood extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>Types of Food:</h1>
      </div>
    );
  }
};

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

And then here is the html:

<!DOCTYPE html>
<html>
<head>
	<title>NewApp 1</title>
</head>
<body>
	<div id="app"></div>
	<script src ='script.js'></script>
</body>
</html>

#2

Hey there, so part of your problem might be that you’re not exporting the React component you wrote. Also, I think you’d have to import that component as well


#3

One thing is that in the html you need to include links to the react and react-dom libraries.
For example:

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>

<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

Maybe something else.

See also https://reactjs.org/docs/hello-world.html


#4

Specifically, I’d try adding a line of code: “export default TypesOfFood;” in your React code, right above your ReactDOM.render(…).

Then create a seperate file, within the same folder as your React component. Name it anything (I ususally prefer app.js), and in it write one line:
import TypesOfFood from "./(name of your React component file)"

Next, in your HTML, include a script tag linking to your app.js file (I’ll assume you know how to do this already).

You should also include the links to the CDNs like zdflower said.

Maybe try this and see if it works?