Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing react into pages in next.js

I have a Next.js app with several pages in it. All of the pages look similar.

import React, { Component } from "react";
import  from "components/Wrapper";

export default class About extends Component {
  render() {
    return <Wrapper />;
  }
}

I would like to refactor it using functional component.

I read here that you don't have to import react package here in a page due to next.js routing system. Next.js docs also show examples without react import on a page component, but no explanation given.

Can you clarify please. Is it necessary to import React at all in this case? Can I remove the import React line?

like image 736
kilogram Avatar asked Jul 25 '20 15:07

kilogram


People also ask

Do you import React from Nextjs?

Next. js automatically adds the React import when JSX is used indeed. However, keep in mind that we still need to import React from 'react' when the React variable is used. So this will show us, that whenever we want to use the JSX feature alone from React we do not have to import React from 'react' and Next.

Can I use React packages in next JS?

To add Next. js to your project, you will not need to load the react and react-dom scripts from unpkg.com anymore. Instead, you can install these packages locally using the Node Package Manager: npm . Note: You will need to have Node.


1 Answers

Well, actually it is still a complicated issue for all of us to realise when to use import React from "react"; and when not to in Next.js apps. But according to Tim Neutkens co-author of Next.js, in this thread he mentioned:

Next.js automatically adds the React import when JSX is used indeed. However, keep in mind that we still need to import React from 'react' when the React variable is used.

So this will show us, that whenever we want to use the JSX feature alone from React we do not have to import React from 'react' and Next.js will implicitly import it for us, but in any other case, we have to do that.

Update

Since the release of react v17.*.*, there is no need to import React from 'react' to use only JSX in the React and CRA apps, but you still need to import it for the usage of the hooks and other compartments that React offers.

like image 100
SMAKSS Avatar answered Oct 07 '22 17:10

SMAKSS