Skip to content
Advertisement

Cannot read properties of undefined (reading ‘value’)

this is very basic but I’m new to JS and new to React, I need a few pointers on what I’m doing wrong. I have a Slider components I would like to change, and I would like to reflect/store the new value of the Slider in the class state. How should I be writing this?

I get this error:

TypeError: Cannot read properties of undefined (reading 'value')

Code example below:

import React from 'react';
import { Text, View, Button } from 'react-native';
import Slider from '@react-native-community/slider';
import { TextInput } from 'react-native-paper';

class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        value1: 1
      };
    }

    render() {
        return(
            <View>
                <Text>Slider</Text>
                    <Slider 
                    value={this.state.value1}
                    onValueChange={(e) => this.setState({value1: e.target.value})}
                    minimumValue={1}
                    maximumValue={5}
                    step={1}/>
          </View>
      );
    }
  }
  
export default App;

Advertisement

Answer

there is no mood property in your code, I highly recommend you to work with functional components instead of class components to be able to use hooks and make your code more clean and readable. for more information check React Functional Components VS Class Components

I revised your code, now it updates the state of value1 whenever the slider moves:

import React from 'react';
import { Text, View, Button } from 'react-native';
import Slider from '@react-native-community/slider';
import { TextInput } from 'react-native-paper';



    const App = (props) =>{
      const [value1 , setValue1] = React.useState(1)


        return(
            <View>
                <Text>The value is : {value1}</Text>
                    <Slider 
                    value={value1}
                    onValueChange={setValue1}
                    minimumValue={1}
                    maximumValue={5}
                    step={1}/>
          </View>
      );
    
  }
  
export default App;

demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement