Adjust the child content within a React component based on the element's width, rather than the overall window size, by implementing dynamic resizing without fixed breakpoints

I am working with a react component that displays a div containing menu items which are aligned horizontally using inline-block.

The menu items have text labels "Toy Store", "Configure your Toy", and "About Us".

My challenge is to dynamically change the text of these menu items based on the window size. Specifically, I want the text to change to "Toys", "Configure", and "About" when the parent element can no longer fit them in one line due to reduced width. If the space becomes too narrow even for this, I need the text to be shortened to just "T", "C", and "A" respectively.

Given that this involves both style and content changes, how can I achieve this functionality using a react element?

render () {

    const { theme } = this.props;
    const { classes } = this.props;

    return(
        <div style={{flex: 1}}>
            <Button color="inherit" variant={this.state.btnVar0} onClick={(e) => this.toggleMenuBtns(0,e)}><span className = {classes.menuButtonMed}  >T{this.state.squeeze > 1 ? null : <span      >oy</span>}</span>{this.state.squeeze > 0 ? null : <span> Store</   span>}</Button>
            <Button color="inherit" variant={this.state.btnVar1} onClick={(e) => this.toggleMenuBtns(1,e)}><span className = {classes.menuButtonTreat}>C{this.state.squeeze > 1 ? null : <span>onfigure</span>}</span>{this.state.squeeze > 0 ? null : <span> your Toy</span>}</Button>
            <Button color="inherit" variant={this.state.btnVar2} onClick={(e) => this.toggleMenuBtns(2,e)}><span className = {classes.menuButtonCom}  >A{this.state.squeeze > 1 ? null : <span    >bout</span>}</span>{this.state.squeeze > 0 ? null : <span> Us</      span>}</Button>
        </div>

    );
}

Answer №1

In order to avoid relying on preset breakpoints, you will need to dynamically calculate the width of your menu elements and compare it to the width of the client window. If the total width of your menu elements is greater than that of the window, you can update the content of the menu elements with their shorter alternatives in sequence.

This calculation would need to be performed both upon initial rendering and whenever a window resize event occurs.

One method for conducting this width comparison could involve utilizing a combination of React Refs, Element.clientWidth, and window.innerWidth.

Regarding the process of switching between different text alternatives, there are multiple approaches you could consider (such as using CSS, directly updating text content, leveraging state and/or props, etc.).

I encourage you to explore these implementation strategies further on your own.

Answer №2

Take a look at my solution on JSFiddle,

Make sure to check out the JSFiddle by adjusting the output window size.

While not flawless, this will provide you with a starting point.

I utilized css content:attr(attib-name) for this solution.

I defined 3 attributes: data-small, data-med, data-big

 <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>

and then I implemented

.inline:after {
  content: attr(data-big);
  display: block;
  text-align: center;

}

@media(max-width:768px) {
  .inline:after {
    content: attr(data-med);
  }
}

@media(max-width:500px) {
  .inline:after {
    content: attr(data-small);
  }
}

To assign different values.

* {
  box-sizing: border-box;
}

body {
  padding: 20px;
}

.parent {}

.inline {
  border: 1px solid black;
  display: inline-block;
  min-width: 50px;
  position: relative;
  padding: 5px 10px;
}

.inline:after {
  content: attr(data-big);
  display: block;
  text-align: center;
}

@media(max-width:768px) {
  .inline:after {
    content: attr(data-med);
  }
}

@media(max-width:500px) {
  .inline:after {
    content: attr(data-small);
  }
}
<div class="parent">
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
  <div data-small="T" data-med="Toys" data-big="Toys Stuff" class="inline"></div>
</div>

Answer №3

https://i.sstatic.net/rbWa6.pngYou can easily create this layout using bootstrap. https://i.sstatic.net/s5ftv.png Here is the code snippet:

<ul className="nav navbar-nav">
        <li>
          <a>
            <span className="hidden-lg">Toys</span>
            <span className="hidden-xs">Toy Store</span>
          </a>
        </li>
        <li>
          <a>
            <span className="hidden-lg">Configure</span>
            <span className="hidden-xs">Configure your Toy</span>
          </a>
        </li>
        <li>
          <a>
            <span className="hidden-lg">About</span>
            <span className="hidden-xs">About Us</span>
          </a>
        </li>
      </ul>

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

Tips for preventing images from stretching the width and height of my HTML

I am facing an issue with my SVG files positioned as "absolute" on my page. When they are close to the corners of the page, they end up expanding the width of my Container element (using Material UI React). I have tried setting "maxWidth":"100vw" on the ...

Issue with Firefox translateZ causing only half of the content to be visible on initial load in Pure CSS Parallax configurations

Recently, I've been experimenting with creating a parallax website and have been following the helpful steps outlined by Keith Clark. However, I've run into an issue that seems to be specific to Firefox. Upon loading the site, I noticed that the ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Is the image loading promptly? Do we need to adjust the resolution?

Is there a way to decrease the loading time of images? For instance, if I have 20 identical images on my homepage (each sized at 1920x1080) This is the image: I want to crop the image to a fixed size. Here's the CSS code I am using: .startpage_im ...

Explore the world of textures transferring from Maya to Three.js

I'm looking to convert a Maya model to JavaScript for a simple model with textures. The conversion works fine, but the textures are not showing up. Here is my code: var loader = new THREE.JSONLoader(); loader.load( "models/t2.js", function(geometry) ...

What is the best way to apply CSS max-left or min-left positioning to an absolute element?

I currently have an element with the CSS properties: position:absolute; left: 70%; Is there a way to restrict this element from moving more than 900px from the left side? Similar to max-width but for positioning? ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

Troubleshooting the issue of array filtering not functioning properly in Async.js

When attempting to utilize async's filter method, I am not receiving the expected result. Could someone point me in the right direction? async.filter([1, 3, 5], function (item, done) { done(item > 1); }, function (results) { con ...

What are some alternative ways to arrange this main navigation bar?

Check out the website, below the map you'll find an unordered list: HTML code: <ul class="play_navigation"> <li class="active"><a href="#" class="barino_story_bottom">The Story</a></li> <li><a href="#" ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

Suggestions for stopping the errors when using npx create-react-app

Attempting to kick off a react project by running the command npx create-react-app dashboard, but encountering this error: npm ERR! code ENOENT npm ERR! syscall rename npm ERR! path /home/<myfolder>/.npm/_cacache/tmp/33c12b20 npm ERR! dest /home/< ...

Creating a unique WooCommerce product category dropdown shortcode for your website

I am having trouble implementing a WooCommerce categories dropdown shortcode. Although I can see the drop-down menu, selecting a category does not seem to trigger any action. Shortcode: [product_categories_dropdown orderby="title" count="0" hierarchical=" ...

Innovative sound system powered by React

I am working on implementing a music player feature on a website where users can select a song and have it play automatically. The challenge I am facing is with the play/pause button functionality. I have created all the necessary components, but there see ...

Changing the color of a pseudo element in Material-UI

I'm having trouble changing the border color of the ::after pseudo element on a standard text field from MUI. I've been unable to figure it out. <TextField id="standard-basic" label="Email" variant="standard"/> ...

Is there a way to change this from webkit to moz?

Is there a way to change this code from webkit to moz? background-color: #fff; background-image: -moz-linear-gradient(0deg, transparent 79px, #ABCED4 79px, #ABCED4 81px, transparent 81px), -moz-linear-gradient(#EEE .05em, transparent .05em); ...

What is the best way to clear the cache in AngularJS?

It is crucial for the cache to be cleared consistently. However, no matter if a client is created, updated, or deleted, the same result always occurs. Only when I manually delete the cache (Ctrl+Shift+Supr), am I able to view the new data. .factory(' ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

How can I activate a route without changing the URL in AngularJS?

Is there a way to activate a route and display a different view in Angular without changing the URL? I have integrated an Angular app into an existing website, and I prefer not to modify the URL within my embedded application, but would still like to mana ...

Is there a way for this SVG graphic to adjust its size to fit its container without manual resizing

Click here to view the demo In the demo, there is an SVG star placed inside a div with specific width and height. I am looking for a way to make the graphics adjust automatically to fit the size of the wrapper div. Since it's a vector graphic, I beli ...

How can I use CSS to ensure that both cards and images are equal in size?

I am currently utilizing react, with Material-ui being used for the Cards. For the layout, I have implemented CSS Grid Layout for the Grid system. Presently, the structure looks like this: https://i.stack.imgur.com/0FDyY.png However, my desired outcome i ...