Handling multiple conditions can be done in different ways in programming, such as using If

I am new to React and trying to implement conditional styling based on screen size. Despite searching the internet, I couldn't find a solution that works for me. Specifically, I want to center some text based on the screen size. Can anyone suggest a better way to achieve this? Currently, my approach is not yielding the desired results.

Update: After adding some logs, I noticed that the 'textAlign' property is not being applied to the element when the screen size is greater than 993px initially. However, it does get set to 'center' between 578px and 993px, but fails to revert back to its original state once the screen size decreases below 578px. It remains centered instead of resetting.

const styles = {
    footerColOne:{
        textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
        paddingLeft: deviceSize < 993 ? "26px" : "80px",
        paddingTop: deviceSize < 993 ? "28px" : "63px",
    },
    footerColTwo:{
        textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
        paddingLeft: deviceSize < 993 ? "26px" : deviceSize < 578 ? "51px" : "50px",
        paddingTop: deviceSize < 993 ? "40px" : "86px",
    },
  }

To implement these styles, I'm using the following:

<Col lg={3} style={ styles.footerColOne }>

Any assistance would be greatly appreciated.

Latest Update:

Upon further reflection, I've realized that using media queries would be a more suitable approach for this task. While my ternary condition above did work, I mistakenly set 'textAlign' to 'none', which is an invalid value for that property. Instead, it should be set to 'initial' in this scenario.

Answer №1

media query is the perfect solution for this situation.

@media screen and (min-width: 578px) and (max-width: 993px) {
  .someclass {
   text-align:center;
  }
}

@media screen and (max-width: 993px) {
  .someclass {
   text-align:center;
   padding-left:26px;
   padding-right:28px;
  }
}

@media screen and (min-width: 993px) {
  .someclass {
    text-align:left /* as you requested. /*;
  }
}

Therefore,

max-width determines when styles within its media query are applied based on screen size being below that width.

min-width triggers the styles inside its media query to be applied only if screen size exceeds the specified width.

Answer №2

function determineDevice(deviceResolution) {
    if (deviceResolution < 993) {
        if (deviceResolution < 993 && deviceResolution > 578) {
            return 'tablet';
        } else {
            return 'mobile';
        }
    } else {
        return 'web';
    }
}

// If CSS is declared, return a class
// Components should use className instead of styles
// <Col lg={3} className={...} />
const footerColOne = {
    'web': () => {
        return {
            textAlign: 'none',
            paddingLeft: '26px',
            paddingTop: '28px'
        };
    },
    'tablet': () => {
        return {
            textAlign: 'center',
            paddingLeft: '80px',
            paddingTop: '63px'
        };
    },
    'mobile': () => {
        return {
            textAlign: 'none',
            paddingLeft: '80px',
            paddingTop: '63px'
        };
    }
};

const styles = {
    footerColOne: footerColOne[determineDevice(deviceSize)]()
};

console.log(styles.footerColOne);

// <Col lg={3} style={styles.footerColOne}>

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

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

css: Aligning fonts horizontally when they have varying sizes

First time asking a question on this platform! I'm attempting to achieve a "pixel perfect" horizontal alignment of two lines of text, with each line having a different font size. <style type="text/css"> * { font-family: sans-serif;} ...

Adjusting the sidebarPanel height to match the mainPanel content in a shiny app

I'm currently developing an app that features a scrollable sidebarPanel alongside a mainPanel that can have varying heights, such as: library(shiny) ui <- fluidPage( headerPanel('Iris k-means clustering'), sidebarPanel(style = " ...

Struggling to figure out the right way to make a CSS selector for the Yahoo stocks page

In my quest to accurately retrieve the number located directly beneath the title with the symbol, I am transitioning from using xpath //div[@class='title']/following::span[2]/text() to experimenting with css selectors in Jsoup. Despite trying var ...

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

React Datepicker on Safari: A seamless way to pick dates

While working on my application, I encountered an issue with the Form.Input functionality from Semantic UI React library. I am using it to insert dates and found that it displays a date-picker on Chrome and Firefox but not on Safari. I attempted to use the ...

Issue with the formatting of the disabled button

I am facing an issue with styling a disabled button. Whenever I try to apply custom styling, it reverts back to the default styling. I have already cleared my cache but the problem persists. The button is disabled using JavaScript with document.getElementB ...

Using jQuery to locate text and apply a specific class

Explaining My HTML Structure: <div id="test-listing"> <article> <a>Some URL</a><h3>Some Text</h3> <p>Drink this coffee</p> </article> <article><a>Some URL</a><h3>Some Text</h ...

IE7 is not applying the conditional CSS styles to content loaded through AJAX

I am currently tackling some challenges with IE7 compatibility in a Rails application that I am developing. It appears that CSS styles implemented from a stylesheet applied with a conditional comment are not being rendered properly when using HAML like thi ...

Rewrite all uhttpd routes to point to the root directory

I am currently in the process of configuring a react application with react router on an embedded device served by uhttpd. My challenge lies in redirecting all subroutes (e.g. /foo/bar) back to the root (/). When working with nginx, one could achieve this ...

I often find that jscodeshift consistently avoids processing my JavaScript files

I am currently in the process of updating my react application to the newest version of Material-UI. I came across a migration helper script using jscodeshift within the material UI project. (https://github.com/mui-org/material-ui/tree/master/packages/mate ...

Adding more pixels to the height of an element does not actually make it larger

Recently, I've been working with material UI and I have a scrolling list of items that I want to resize to be larger. However, I've noticed that no matter how I adjust the height in pixels, the items never exceed 140px. Below is the code snippet ...

Update the CAPTCHA, while also refreshing the entire registration form

JavaScript Snippet <script language="javascript" type="text/javascript"> function updateCaptcha() { $("#captchaimage").attr('src','new_captcha_image.php'); } </script> New Image Code <img src="new_ ...

New to React - onBlur Event Causes Element to Lose Focus

Attempting to construct a simple login page that collects user credentials and transmits them to a login API. Encountering an issue where, upon triggering the onChange, which sets the user credentials, the element loses focus. Is it advisable not to update ...

Can you explain the significance of (.browser-default).valid?

While exploring some code online, I came across this snippet: input[type=text]:not(.browser-default).valid. I understand the purpose of the :not selector in this code, but I have a couple of questions: What is the role of (.browser-default) in this c ...

There appears to be no overload that aligns with this call using styled components (index.d.ts(2187, 9))

Trying to create an Input component using styled components that accepts props but encountering an error when using the onChange prop - No overload matches this call. It seems like there might be an issue with my types, but even after extensive research, I ...