How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components.

Here's the issue:

In React Native, I utilize flex properties to manage View dimensions, like this:

<View style={{ flex: 1 }}>
    <View style={{ flex: 0.5, backgroundColor: 'blue' }}>
      <Text>I'm a blue 50% screen View!</Text>
    </View>
    <View style={{ flex: 0.5, backgroundColor: 'yellow' }}>
      <Text>I'm a yellow 50% screen View!</Text>        
    </View>
</View>

However, when working with React JS, I can't use flex properties with div tags as they don't support it. This means I can't achieve the same layout using the following code:

<div style={{ flex: 1 }}>
    <div style={{ flex: 0.5, backgroundColor: 'blue' }}>
      <p>I'm a blue 50% screen View!</p>
    </div>
    <div style={{ flex: 0.5, backgroundColor: 'yellow' }}>
      <p>I'm a yellow 50% screen View!</p>        
    </div>
</div>

Could someone guide me on how to apply these styles in React JS for the div elements to attain the desired percentage-based results?

Answer №1

When working with React Native, it utilizes its own flexbox implementation which can be found here: https://facebook.github.io/react-native/docs/flexbox

In contrast, React utilizes CSS flexbox which is explained in detail here: https://developer.mozilla.org/en-US/docs/Glossary/Flexbox

Although the concept of flexbox remains consistent between React Native and web-based CSS, there are a few distinctions to note. For example, flexDirection defaults to column in React Native rather than row, and the flex parameter only accepts a single number value.

In CSS, it is essential to declare the parent container as follows:

.flex-container {
  display: flex;
}

If you are encountering issues, chances are you may have overlooked this crucial step.

The pure CSS version of your flex implementation might resemble something like this (styles written as "string" version):

<div style="display: flex; flex-direction: column; height: 100vh;">
    <div style="flex: 1; background-color: blue;">
      <p>I'm a blue 50% screen View!</p>
    </div>
    <div style="flex: 1; background-color: yellow;">
      <p>I'm a yellow 50% screen View!</p>        
    </div>
</div>

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

Adjustable React-icons for dynamic icon sizing

What is the best way to reduce the size of react-icons icons for mobile devices without using pixel values? import { FaSearch, FaFacebook, FaInstagram, FaUserCog, FaUserTimes } from "react-icons/fa"; <FaSearch color="#02337 ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Ensure Your Forms Are Error-Free with Jquery Form Validation

Currently working on a registration form that involves the use of credit cards. I have reached the stage of form validation to ensure that users input correct data in the appropriate fields. However, this has led me to ponder whether relying on JQuery for ...

It is impossible in JavaScript for document.getElementById to be null, even when the element is present in the DOM

While using a component in React, I encountered an issue where I have an <input type="text" id="location" />. In the componentDidMount() of this component, I attempt to search for this element. componentDidMount(){ debugger; let ele = docume ...

A unique feature where a bar emerges from the bottom of the screen, smoothly glides upwards, and then securely fastens to

I'm working on bringing to life a concept that I've been envisioning. The design would feature a long scrolling page with a unique navigation bar behavior. The idea is for the navigation bar to initially start at the bottom of the screen and the ...

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

Header misalignment occurs when the user scrolls up too quickly causing it to display

One interesting feature on my website is that the header disappears as users scroll down the page, but reappears when they start scrolling back up, even if they are halfway down. However, if a user quickly scrolls up and down, there seems to be an issue wi ...

What is the best way to smoothly reveal images one by one?

My goal is to smoothly slide three images inside a div, one by one. However, I'm facing an issue where the images stack on top of each other and end up stuck in their original positions. Here is the code snippet I've been working with: <div ...

Update the content inside a <p> tag dynamically using Javascript based on the selected option

Struggling with Javascript and need some guidance. I have a select box with 4 options, and I want to update the contents of a <p> tag with an id of pricedesc based on the selected option. Here is my current code: function priceText(sel) { var l ...

Progress bar for AJAX file loading for Flash player

Looking to create a progress bar using AJAX for a flash file. Check out this demo here: I tried to analyze their page, but the JavaScript is encrypted and I'm not very skilled in JS. Any suggestions? Thank you! ...

Encountered a NetworkError while trying to access the resource for Passport ReactJS and ExpressJS: CORS issue

I am currently working on a project where the front-end is developed using React JS at http://localhost:3000/ and the backend using Express JS at http://localhost:5000/ Google Console Details React Login Page : Clicking on login using Google const _han ...

Expanding a feature that modifies the CSS properties of every input element

Creating a text tracking (letter-spacing) demonstration where range sliders are used to update CSS properties. I'm looking to improve the functionality so that the labels also update dynamically, without repeating output2.textContent = this.value;. An ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Tips for accessing another page when location.state is missing

In my react application, I am passing state through react router and accessing it in the target component/page using the location object. Everything works perfectly fine initially, but when I close the tab and try to open the same page by pasting the URL i ...

Is there a way to activate a click event on a particular child element within a parent element?

When attempting to click on a specific descendant of an element, I located the ancestor using ng-class since it lacked an id. yes = document.querySelectorAll('[ng-controller = "inventoryController"]') Having found the desired ancestor, ...

Tips for encoding AngularJS ng-model in real-time

Recently, I embarked on a new project and wanted to incorporate some AngularJS magic. The only obstacle is my limited expertise in AngularJS or JavaScript, making it difficult for me to figure out how to make it work. One key requirement is that the functi ...

Service workers do not support fetching from .html files

Struggling with creating a functioning service worker for offline use has been a challenge. Despite trying numerous examples, the success has remained elusive. Initially, I suspected that the dynamic nature of my PHP-based website was causing the issue, or ...

When attempting to update a task with the Microsoft Graph API, the server returned a 400 error code

Attempting to update a Task using the Graph API from an angular2 typescript app. Here is an example of my request - Request URL:https://graph.microsoft.com/beta/tasks/_1EKXXuN1UGInJ9yVHAjIpYAKuC2 Request Method:PATCH Request Body: { "createdBy":"f16 ...

Utilize JavaScript to create a toggle menu feature that can target multiple variables with just one click function

I am attempting to create a collapsing menu on click functionality with additional modifications. One of the changes I would like to implement is altering the background of another element when the menu collapses. Currently, the code snippet only works fo ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...