Home > Back-end >  What is wrong with this Component of React native ? I want to change color of square block on button
What is wrong with this Component of React native ? I want to change color of square block on button

Time:11-14

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

const ColorScreen = () => {
  const [color, setColor] = useState(0);

  const changeColorHandler = () => {
    setColor(Math.floor(Math.random() * 100));
  };

  return (
    <View>
      <Button onPress={changeColorHandler} title="Add Random Color" />
      <View
        style={{
          height: 100,
          width: 100,
          backgroundColor: `rgb(${color}, ${color}, ${color})`,
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({});

export default ColorScreen;

Color of Square block NOT changing on button press

Also suggest me some good small exercises to learn react and react native

CodePudding user response:

Your R, G, and B levels should also be independent. Otherwise, it will show a varients of black color.

Try this

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

const App = () => {
  const [color, setColor] = useState({ r: 0, g: 0, b: 0 });

  const getRandom = () => {
    return Math.floor(Math.random() * 225);
  };

  const changeColorHandler = () => {
    setColor({ r: getRandom(), g: getRandom(), b: getRandom() });
  };

  console.log(`rgb(${color}, ${color}, ${color})`);

  return (
    <View>
      <Button onPress={changeColorHandler} title="Add Random Color" />
      <View
        style={{
          height: 100,
          width: 100,
          backgroundColor: `rgb(${color.r}, ${color.g}, ${color.b})`
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({});

export default App;

Code sandbox => https://codesandbox.io/s/react-native-web-forked-hwn0e?file=/src/App.js:0-762

  • Related