The issue with setting width using % in React Native is causing trouble

While working on my project using expo react native, I encountered an issue with a horizontal scrollview for images. When I style the images using pixels like this:

<Image code... style={{width: 350}}/>
, everything works fine. However, if I try to change the pixel value to a percentage - 35% - the image disappears from the screen. I've tried various solutions to fix this problem, including adding a 100% width viewport for the parent class as shown below, but it still doesn't seem to work.

Here is the snippet of the code:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Image, ScrollView, Modal, Pressable } from 'react-native';
tw from 'tailwind-react-native-classnames';
import React, { useState } from 'react';

export default function ImpEvents() {
    const slides = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    const [modalVisible1, setModalVisible1] = useState(false);

    // Additional modal states and functions

    return (
        <View style={{width: '100%'}}>
            // Modals and their setup

            <Text style={{ left: 40, fontFamily: 'OpenSans_700Bold', marginTop: '70%', fontSize: 25, color: "#3D3D3D" }}>Important Information</Text>

            <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10 }}>
                <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={{ paddingTop: 7, paddingLeft: 40 }} snapToInterval={370} decelerationRate={0}>
                    // Pressables and images

                    </ScrollView >
            </View>
        <View/>
    )
}

The issue arises when trying to display the image at index 0 while using percentages, whereas images at indices 1 and 2 are displayed correctly without using percentages.

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

To utilize the % symbol, you must specify a width for the parent component. Alternatively, you can dynamically obtain the device's width in react native by using the Dimension method outlined below:

import { Dimensions } from 'react-native';

const DeviceWidth = Dimensions.get('window').width;

To assign a width of 90% based on the device's width, you can implement it with the following code: width: DeviceWidth * 0.9.

Answer №2

The reason for this issue is that the parent component <Pressable> does not have the necessary width style specified. If you want to use dynamic height or width in percentage, you need to ensure that the parent component has both height and width defined.

Simply add width: "100%" to the parent component and then troubleshoot from there. If that doesn't solve the problem, investigate the parent component of the parent component and work your way back through the structure.

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

Issue with CKEditor 5 in Nuxt 3: "Template or render function for component is not found"

I have successfully installed the required packages: npm i @ckeditor/ckeditor5-build-classic @ckeditor/ckeditor5-vue Next, I integrated it into a component: <template> <div class="w-full h-[400px]"> <CKEditor v-mod ...

Tips for choosing a specific quantity and adjusting its value

Just starting out with Ionic 3 and looking for some help with the code. Can anyone assist me in understanding how to change the value of an item in a shopping cart and have the subtotal reflect that change? cart.ts private _values1 = [" 1 ", "2", " 3 "," ...

The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the sam ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

Troubleshooting React TypeScript: Resolving the Error "Argument of type ''""' is not assignable to parameter of type 'SetStateAction<undefined>'"

Currently, I am troubleshooting a React application that was extracted from a live server and now I am attempting to run it on my local machine. However, upon starting up the application locally, I encountered the following error message: Argument of ty ...

Middleware in Express.js Router

In the following code snippet, I am aiming to limit access to the 'restrictedRoutes' routes without proper authorization. However, I am encountering an issue where 'restrictedRoutes' is affecting all routes except for those within the & ...

Toggle button in VueJS that dynamically shows/hides based on the state of other buttons

In my table, I have included options for the days of the week such as Everyday, Weekdays, and Weekend. Each row contains 2 select items to choose start and end times for updates. Additionally, there is a toggle button at the end of each row that enables or ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Securing your Angular2 application with TypeScript for enhanced safety

Looking to create a web application using Angular2 with TypeScript. After researching authentication in Angular2, it seems I need to include the following components: index component (public) login component (public) my private component (private) Thes ...

Troubleshooting jQuery: Unable to refresh the webpage

I have a PHP page that contains a form, checkboxes, and a submit button. I added an if statement to execute a PHP script I created when the button is clicked, which deletes certain values from the selected rows. The button functions properly and changes s ...

Encountered error: Unable to locate module - Path 'fs' not found in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib' within newly generated Chakra application

Started by creating the app using yarn create react-app chakra-ts --template @chakra-ui/typescript. Next, added dotenv with yarn add dotenv Inserted the following code block into App.tsx as per the instructions from dotenv documentation: import * as dote ...

I am attempting to retrieve the aria-expanded value using JavaScript, however, I keep receiving an "undefined" response

I'm attempting to dynamically change the class of a <span> element based on the value of the attribute aria-expanded. However, I am encountering an issue where it returns "undefined" instead of the expected value of true or false. Below is the ...

Guide: Extracting a targeted input field value from an external webpage with Javascript

After successfully retrieving the webpage content from an external website using ajax, my next goal is to develop a function that can extract a specific input field value which is already pre-filled. The structure of the webpage content looks something li ...

Resetting the initial values in Formik while utilizing Yup validation alongside it

Currently, I am working on a React application with Typescript and using Formik along with Yup validation. However, I have encountered an issue with setting values in a Select element. It seems that the value is not changing at all, or it may be resettin ...

Next JS now includes the option to add the async attribute when generating a list of script files

We are currently working on a nextJs application and are looking to add asynchronous functionality to all existing script tags. Despite numerous attempts, we haven't been successful in achieving this. Can anyone provide some guidance or assistance? &l ...

How can I make a div or iframe stretch to fill the remaining space using javascript, jQuery, or css?

I'm looking for a way to make the middle iframe dynamically fill the remaining space between two fixed height iframes (one at the top and one at the bottom) regardless of the window screen size. Is there a technique or method that can achieve this? th ...

The ExpressJS middleware is executing twice

I'm experiencing an issue with the following code snippet. When I include the middleware logger() as the first argument to app.use(), it is called twice. However, when I place it as the second argument, it doesn't get executed at all. Can anyone ...

Using Antd to configure the state property of menu items

The use of the mapping method for rendering sub menu items is ineffective. The current state needs to be addressed in this particular class. class SideBar extends React.Component { constructor(props) { super(props); this.state = { fruits:["or ...

Exploring the features of useEffect and setState in hook functions

Exploring the idea of utilizing React to efficiently fetch data using useEffect correctly. Currently facing a situation where data fetching is occurring constantly instead of just once and updating only when there is an input for the date period (triggeri ...

Creating a Sleek MenuBar in JavaFX

At the top of my BorderPane, I have added a MenuBar containing a "File" Menu and a "Close" MenuItem: I want to make it appear thinner like the MenuBars in most software applications, similar to the image below: It seems like a simple task, but as a begin ...