I am making a next js application (React SSR), and now I am into implementing the meta tags in head.
So for now I have used next/head in _app.tsx file like,
import React from 'react';
import App from 'next/app';
import Head from 'next/head';
import { ThemeProvider } from '#material-ui/core/styles';
import CssBaseline from '#material-ui/core/CssBaseline';
import theme from '../src/theme';
export default class MyApp extends App {
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement!.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps } = this.props;
return (
<React.Fragment>
<Head>
<title>My page</title>
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</React.Fragment>
);
}
}
And the whole working code can be found here at sandbox: https://codesandbox.io/s/interesting-tereshkova-217ks
I am just to know whether using next/head itself enough in next js application or else need to implement react-helmet ??
If the react-helmet is needed then kindly help me how to implement in the provided next js application.
I am new into Next Js and SSR, So please help me in right direction which is the best method to achieve the result.
I am just to know whether using next/head itself enough in next js application or else need to implement react-helmet ??
react-helmet makes sense to use if you're rolling your own server side rendering solution and are not using Next.js. As far as I know, next/head is bascially a built-in version of react-helmet and does everything react-helmet does.
So no, you don't need to use react-helmet if you are using Next.js. Just use next/head.
If the react-helmet is needed then kindly help me how to implement in the provided next js application.
That said, if you want to use react-helmet with Next.js, here is an example: https://github.com/zeit/next.js/tree/canary/examples/with-react-helmet. Not sure why you'd do this, but the example exists. There is some discussion about it.
By the way, just like react-helmet, you can use next/head anywhere in your render tree—not just the App component like in your example—and all the tags will be aggregated into the <head> tag at the top.
There is also a great package for Meta tags for Next JS
next-seo
Related
After using Vue and Nuxt for more than a year, I decided to learn React and Next.js and almost immediately noticed the horrible Developer Experience.
Every stylesheet and component needs to be imported so there's always bloated import hell at the start of each component.
Not to mention if you need an extra library as you can't hook into any global object like Nuxt's this.$plugin option.
Is there some package to manage these imports for Nextjs? As far as I know, everyone who uses it doesn't mind it and that's what surprises me.
This Question may come as an insult to React and it is, but I just want at least one reason to join the hype-train as to why React is more popular.
create a file in pages directory named it _doucument.js or _document.ts (for TypeScript) and import React in it like below :
(below codes are TypeScript)
import React from 'react';
import Document, {
DocumentContext,
Head,
Html,
Main,
NextScript,
} from 'next/document';
export default class CustomDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head>
<title>Your title</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
and any more doesn't require that import React in any components.
Is it possible to add a build index.html of a React app to a div in my HTML/ColdFusion website?
I built a chatbot in React using hooks.
Bellow is my App.js which imports my ChatBot.js component.
import './App.css';
import MyChatBot from './ChatBot';
function App() {
return (
<div className="App">
<MyChatBot/>
</div>
);
}
export default App;
It is working. I have a ColdFusion/HTML website where I would like to include this "chatbot" or the generated index.html from npm run build to a div
<!-- ColdFusion Website here --->
<div id="myChatBot"></div>
The idea is to have the React application inside that div. Is it possible?
Thank you.
Yes, you can. You just need to pass the element ( where you want to mount the react app ) to ReactDOM.render method. Then bundle your react app using a bundler, say webpack, and include that bundle via script tag or via the current build process in your app's html.
HTML
<!-- Website Markup --->
<div id="myChatBot"></div>
<!-- Include React bundle --->
<script src="bundle.js"></script>
React
import ReactDOM from "react"
import App from "./App"
ReactDOM.render(<App/>, document.getElementById("myChatBot"))
Hope this is helpful to you: https://reactjs.org/docs/add-react-to-a-website.html
Gist of it is you have import the React scripts and render it to that id:
const domContainer = document.getElementById('myChatBot');
ReactDOM.render(e(LikeButton), domContainer);
I'm using NextJS and Styled Components. Reading the documentation below I added a custom _document.js in NextJS to make Styled Components works.
Styled Components Doc
The example code is written in a React Class, is there a way of converting this to a function?
This is possible since Next 11.1.1, thanks to #28515, but the feature seems currently undocumented.
See an example below:
import { Html, Head, Main, NextScript } from 'next/document'
const Document = () => (
<Html>
<Head/>
<body>
<Main />
<NextScript />
</body>
</Html>
)
export default Document
The answer is that there is no good way to do it, I guess you could somehow override it but Next.js uses _document and _app for in its custom runtime and it is not a good idea to override it.
_document's purpose:
A custom Document is commonly used to augment your application's <html> and <body> tags.
Also, note that using any logic (apart from this inside getInitialProps) inside _document is unadvisable: https://nextjs.org/docs/advanced-features/custom-document#caveats
I just watched a talk from React Conf 2018. In the video, the speaker shows 2 ways to set the document title. The first is by using the Lifecycle methods (componentDidMount and componentDidUpdate) if we use a class component, the second one is by using the useEffect hook if we use a function component. It looks like that's the recommended way to do it according to answers from this question.
But, I tested the following code and it seems to work just fine to set the document title directly:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
document.title = 'wow'
return <p>Hello</p>
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
The title changed:
Is there any significance of setting the document title inside useEffect or componentDidMount?
Or is it because it was the only way to set the document title?
Is it okay to set the document title directly like I did in the snippet above?
Update:
It also works with class component:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
document.title = 'wow'
return <p>Hello</p>
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
The thing is, the render function in React, is considered to be a pure function.
A pure function should not have any side-effects. Eventually updating the document.title means that you are referencing the document directly from render-> which is already considered a side effect.
Render should mainly do one thing -> render some JSX, if there is a need to do some API calls/interact with the document/window etc..., this should be placed in componentDidMount/componentDidUpate for a class Component, OR in a useEffect/useLayoutEfect for a functional component based on hooks.
(useEffect for e.g. is a function that runs asynchronously, and updating the document title from it will not block the rendering, whereas doing it directly will block it.)
Use react-helment which is also widely used in other frameworks with the same name as helmet express ...
Here is the same code:
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://example.org/example" />
</Helmet>
...
</div>
);
}
};
Another way to use via props to which is cleaner IMO
...
<Helmet titleTemplate={`%s | ${props.title}`} defaultTitle={constants.defaultTitle} />
You may also use react-helmet-async for more features.
I'm a newbie learning React. As the next phase of my learning, I need to learn how to style React. From previous experience, the steps I need to take to style my React app are:
Add Reset CSS
Implement a Grid System
Implement common styles for items like (buttons, headers)
Implement specific styles per component
Within the React world it's challenging to find a good jumping off point to tackle the above, so I'd love some advise to point me in the right direction.
Is styled-components most popular thing to do in the React world at the moment for all the 4 items listed above? If not, what do you recommend I start learning to handle the items mentioned above.
If you are starting with React, I'd not go with something deep like styled-components without first understanding the problem styled-components is trying to fix.
Your first approach should be as basic as just add one or more <link>s to your .css files (e.g. reset.css, grid.css, component selectors in it etc.) and use the proper classNames props in your components:
// main.css
body {
// ...
}
// MyToolbar.css
.MyToolbar {
// style for a MyToolbar react component
}
in your html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="stylesheet" type="text/css" href="grid.css">
<link rel="stylesheet" type="text/css" href="MyToolbar.css">
As your app grows, you will find hard to maintain this <head>, so you would benefit from a more modular approach.
For example, your next step may be to import your CSS from javascript instead of using <link> in your header:
// App Component
import React from 'react';
// import globally used styles
import './styles/reset.css';
import './styles/main.css';
export default class App extends React.Component {
// snip
}
To import CSS files in JavaScript, you need to use a module bundler like webpack to handle those imports statements. Start reading here: https://webpack.js.org/guides/asset-management/#loading-css. Doing this way you won't need to manually the CSS files in <head>.
In fact, you will be able to import your CSS from your components:
// MyToolbar.js component
import React from 'react';
import './styles/MyToolbar.css';
export default class MyToolbar extends React.Component {
render() {
// render your component here
}
}
Once your app grows, you may want to experiment with other solutions, e.g. styled-components.