Home > Enterprise >  Importing React First vs Second
Importing React First vs Second

Time:12-12

Why does the following code work:

import React, { useState } from "react";

But when I switch the order around, this DOES NOT work:

import { useState }, React from "react";

And I receive the following error. They are seemingly exactly the same commands just reversed in order. enter image description here

For reference, here's the entire file:

import React, { useState } from "react";
// import { useState }, React from "react";

import MoviesList from "./components/MoviesList";
import "./App.css";

function App() {
    const [movies, setMovies] = useState([]);
    function fetchMoviesHandler() {
        fetch("https://swapi.dev/api/films")
            .then((rsvp) => {
                return rsvp.json();
            })
            .then((data) => {
                const transformedMovies = data.results.map((movie) => {
                    return {
                        id: movie.episode_id,
                        title: movie.title,
                        openingText: movie.opening_crawl,
                        releaseDate: movie.release_date,
                    };
                });
                setMovies(transformedMovies);
            });
    }

    return (
        <React.Fragment>
            <section>
                <button onClick={fetchMoviesHandler}>Fetch Movies</button>
            </section>
            <section>
                <MoviesList movies={movies} />
            </section>
        </React.Fragment>
    );
}

export default App;

CodePudding user response:

Default imports should always be stated first, as the documentation says. You can check the documentation:

Node.js: https://nodejs.org/api/esm.html#import-specifiers

JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

  • Related