0

I'm trying to style a View in React-native but I keep getting this Error (undefined is not an object (evaluating 'styles.screen))

I made a simple code ...

import React, {useState} from 'react';
import {StyleSheet, Text, View, Button, TextInput} from 'react-native';

export default function App() {
  return (
    <View style={styles.screen}>
      <Text>I am testing</Text>
    </View>
  );
  const styles = StyleSheet.create({
    screen: {
      padding: 50,
    },
  });
}

I spent two hours trying to fix this

2 Answers 2

3

This should fix it:

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';

export default function App() {
  return (
    <View style={styles.screen}>
      <Text>I am testing</Text>
    </View>
  );
}
const styles = StyleSheet.create({
  screen: {
    padding: 50,
  },
});

You need to move the const styles object outside of your App() function. The way you have it will return before initialising your stylesheet. An alternative is to place it before your return() inside App() but it is more standard to have it outside.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. I just started learning react-native a couple of days ago, and it's going so slow because all of these errors. thank you again
No problem! I suggest getting familiar with scopes in JavaScript to avoid menacing issues like these in the future. dev.to/sandy8111112004/… provides a pretty good guide.
I appreciate the help
0

So, after troubleshooting for 3 hours and finding no info on this, I finally have the answer. I used a class template search bar React Native Search Bar and created custom styles for said search bar that was being exported from a file, in a folder named 'components' in a parent folder 'app' that was in my '[project]' folder. I imported the class to each screen as it was a header.

The following was an *incorrect import:

import {SearchComponent} from './app/components/searchComponent'

The correct import is:

import SearchComponent from './app/components/searchComponent'

(Because the SearchComponent was exported as a default component and not a named component in the searchComponent.js file.)

Quick reference to default vs named exports

After correctly importing the component, make sure your styles within that component's folder are named correctly and do not share style names with other styles in your destination file; i.e., name of fileA:styleA != name of fileB:styleA.

After checking your exports and imports very, very carefully and checking your style names with the same detail it worked – and it should work for you, as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.