anushka
anushka

Reputation: 123

Function is not working upon click of the button

I have a Button element here at the bottom. onPress somehow is not rendering my function - 'barCharts' - I wonder why it's not showing up the component upon click. I am using buttons from the react-native paper library.

import * as React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Button, Menu, Divider, Provider, TextInput } from 'react-native-paper';
import { BarChart, LineChart, Grid } from 'react-native-svg-charts';
import {  Colors } from 'react-native/Libraries/NewAppScreen';

const App = () => {

  const barCharts = () => {
    const fill = 'rgb(134, 65, 244)'
    const data = [50, 10, 40, 95, -4, -24, null, 85, undefined, 0, 35, 53, -53, 24, 50, -20, -80]
    return (
          <View style={styles.sectionContainer}>
            <BarChart style={{ height: 200 }} data={data} svg={{ fill }} contentInset={{ top: 30, bottom: 30 }}>
              <Grid />
           </BarChart>
          </View>
    );
  };

  const [visible, setVisible] = React.useState(false);
  const openMenu = () => setVisible(true);
  const closeMenu = () => setVisible(false);

  return (
    <Provider>
      <View
        style={{
          paddingTop: 50,
          flexDirection: 'row',
          justifyContent: 'center',
        }}>
        <Menu
          visible={visible}
          onDismiss={closeMenu}
          anchor={<Button onPress={openMenu}>Show menu</Button>}>
          <Menu.Item onPress={() => {}} title="Item 1" />
          <Menu.Item onPress={() => {}} title="Item 2" />
          <Divider />
          <Menu.Item onPress={() => {}} title="Item 3" />
        </Menu>
      </View>
      <View style={styles.sectionContainer}>
        <Button onPress={barCharts}>Show barCharts</Button>
      </View>
    </Provider>
  );
};

export default App;
 

Upvotes: 2

Views: 127

Answers (1)

berlin
berlin

Reputation: 526

you are rendering the entire component inside the button - this will not be able to show. What you actually intended to do is more like

const fill = 'rgb(134, 65, 244)'
const data = [50, 10, 40, 95, -4, -24, null, 85, undefined, 0, 35, 53, -53, 24, 50, -20, -80]
const barCharts = (
          <View style={styles.sectionContainer}>
            <BarChart style={{ height: 200 }} data={data} svg={{ fill }} contentInset={{ top: 30, bottom: 30 }}>
              <Grid />
           </BarChart>
          </View>
    );

<View style={styles.sectionContainer}>
    <Button onPress={() => setShowBarCharts(true)}>Show barCharts</Button>
</View>
{showBarCharts && barcharts}

This would ensure that the barcharts show on the click of the button.

edit: adding a bit for how to change the barcharts component - it is a function currently. i suspect you will have to render a jsx element.

Upvotes: 1

Related Questions