The source code for this blog is available on GitHub.
Note
Top

NEXTJS Hack with some practical usages

Cover Image for NEXTJS Hack with some practical usages
Chen Han
Chen Han

NextJS

Style inside Style JSX

Writing styles in external files

We can also write styles in external files outside of the component.

For example, we can move our global styles from the Layout component into a separate file as follows:

import css from 'styled-jsx/css';
 
export default css.global`
  body {
    margin: 0;
    padding: 0;
    font-size: 18px;
    font-weight: 400;
    line-height: 1.8;
    color: #333;
    font-family: sans-serif;
  }
  h1 {
    font-weight: 700;
  }
  p {
    margin-bottom: 10px;
  }
`;

We can then import the styles back into the Layout component:

import globalStyles from '../styles/global.js';
 
function Layout(props) {
  return (
    <div className="page-layout">
      {props.children}
      <style jsx global>
        {globalStyles}
      </style>
    </div>
  );
}
 
export default Layout;

One-off global selectors

The styles that we add to a component using <style jsx> affect only the elements inside that component, but not child components.

At times, we may need to override a certain style of a child component. To do this, Styled JSX provides :global(), giving access to one-off global selectors.

For example, let's say we have a <Widget> component that contains a button with the class name btn. If we want to change the colors of this button only when the widget is imported on the homepage, we can do so like this:

import Widget from '../components/Widget';
 
function Home() {
  return (
    <div className="container">
      <h1>Hello Next.js</h1>
      <Widget />
      <style jsx>{`
        .container {
          margin: 50px;
        }
        .container :global(.btn) {
          background: #000;
          color: #fff;
        }
      `}</style>
    </div>
  );
}
 
export default Home;

Reference

© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy