Adjusting HTML/JSX in Response to Screen Size

I want to update the text inside a <p> tag depending on the screen size. There are two approaches that come to mind:

  1. Include the text like this:
<p> 
  <span className="one">text one</span>
  <span className="two">text two</span> 
</p>

Then adjust the CSS using media queries, such as:

@media (max-width: 481px) {
  .one {
    display: none;
  }
  .two {
    display: inline;
  }
}

The other option is to use React/JS directly within the component:

let innerText;

React.useEffect(() => {
  if (window.innerWidth <= 481) {
    innerText = 'text one';
  } else {
    innerText = 'text two';
  }
}, [window.innerWidth]);

return (
  <p>{innerText}</p>
);

Which approach is more efficient for this scenario? What is considered to be best practice? Are there any other methods that I should consider? I worry about causing multiple re-renders with the React method when resizing the screen, but also about rendering unnecessary spans with the CSS method.

Answer №1

No need for CSS or creating media queries, thanks to the useIsMobile hook.

const DEFAULT_MOBILE_BREAKPOINT = 1000;

export const useIsMobile = (breakpoint = DEFAULT_MOBILE_BREAKPOINT) => {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const onResize = () => {
      setIsMobile(window.innerWidth < breakpoint);
    };
    window.addEventListener("resize", onResize);
    onResize();
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return isMobile;
};

This versatile hook can be utilized in various components to handle responsive changes effortlessly.

import {useIsMobile} from "../hooks/useIsMobile";

const App = () => {

  const text1 = "Hello World!"
  const text2 = "Goodbye World..."

  return (
    <body className={ useIsMobile(700) ? "dark" : "light" }>

      <p>{ useIsMobile() ?  text1 : text2 }</p>

    </body>
  );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Chrome's display:none latency be eliminated?

My Chrome extension is designed to alter a third-party web page by removing a button and adding two new HTML elements. The process involves observing the URL of the current tab and executing an HTML injection if it matches the specified regex pattern. Desp ...

Issues with loading SASS or source maps arise when dealing with nested structures

After reorganizing my SASS files into a nested structure, I encountered an issue where inspecting elements in Chrome led me to incorrect source maps. For instance, when trying to inspect a button, instead of being directed to the _buttons partial as expect ...

Issue with passing jQuery cookie between two HTTPS pages

I am attempting to transfer a cookie between two secure HTTPS pages using jQuery cookies. The cookie is initially set on page 1 using this code: $.cookie('name', variable, { expires: 300 , secure:true}); Upon navigating to the next page, I try ...

What is the reason for my JSON reference returning as undefined?

Here's my JavaScript code: $.getJSON("/aTest.json", function (jsonObj) { $("#testJSONBtn").click(function () { var val = ""; for (var i = 0; i <= jsonObj.events.length; ++i) { val += jsonObj.events[i].title + ", " + ...

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

How to position the play button in the center using Material UI and Flexbox

Seeking advice on achieving a centered play button with borders in this layout. Struggling with flexbox to position the play button within the code provided. function Tasks(props) { const { classes } = props; return ( <div className={classe ...

Using git mv in VSCode does not automatically adjust TypeScript / JavaScript import paths

Is there a way to successfully move a typescript file in VSCode to achieve both of the following: Ensure Git acknowledges the file continuity Have VSCode update the parent files' import statements I have tried two methods, but each one falls short: ...

Is there a way to send arguments to a pre-existing Vue JS application?

A Vue application we've developed connects to a Web Service to retrieve data. However, the URL of the web service varies depending on the installation location of the app. Initially, we considered using .env files for configuration, but realized that ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...

How can I create a horizontal scrolling page layout?

I have created three different sections, and I want each of them to span the entire width of the screen. I was able to achieve this using the width property, but I am unsure how to make the height 100% of the screen. Additionally, I would like these sectio ...

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

CSS Selectors failing to deliver desired results

Hey, I have a question regarding CSS selectors in relation to my design. I've been experimenting with manipulating checkboxes using CSS and trying to use multiple selectors like "+", "~", etc. to trigger events when the checkbox is checked or uncheck ...

Tips for customizing the WooCommerce product page

If you want to customize the layout of a WooCommerce product page, you can override the template by copying the WooCommerce template folder into your theme. You can find step-by-step instructions here. I am looking to change the layout of a WooCommerce pr ...

The present webpage class within a rails application

In my Rails application, I have a simple navigation bar with links such as Home, News, Contact, etc. I want to dynamically add the class 'active' to the current page link. While exploring different solutions for this, I came up with my own versio ...

Flaws in the implementation of Github pages deployment hindered its

When I attempted to run one of my repositories on GitHub for deployment, I encountered an issue where the CSS and JS contents were not loading correctly. You can access the repository through this link: https://github.com/vipin10100001/agecalculator If yo ...

Tips on displaying a selected choice | Utilizing Material UI Autocomplete

I have successfully fetched data from an API and used it as options in Material UI Autocomplete. However, when I select an option and send it back to the API using a POST request, the selected category is displayed as a number (0) instead of text, as shown ...

My keyframes seem to be malfunctioning, despite exhausting all my troubleshooting options

Could someone please help me figure out why the @keyframes rule is not working for me? I've tried adding -webkit- as a fix, but it doesn't seem to be helping at all. .keyframe { height: 15px; width: 50px; background-color: red; -webkit ...