anushka
anushka

Reputation: 123

Not sure how to render this component with click of a button in react-native

Following is a barChart function. It returns a barChart in the screen-

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>
  );
};

I want this barChart component to render upon click of a button. My current environment is react-native ios. How would I accomplish rendering this upon click of a button in App.js?

Upvotes: 1

Views: 47

Answers (2)

Max
Max

Reputation: 11

You may use props or state for that.

const barCharts = () => {
  const { showBarChart } = this.props;
  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}>
      {showBarChart && (
        <BarChart
          style={{ height: 200 }}
          data={data}
          svg={{ fill }}
          contentInset={{ top: 30, bottom: 30 }}
        >
          <Grid />
        </BarChart>
      )}          
    </View>
  );
}; 

Upvotes: 1

Łukasz Karczewski
Łukasz Karczewski

Reputation: 1218

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 OtherComponent = () => {
    const [clicked, setClicked] = React.useState(false);
    return <View>
        <Button onClick={() => setClicked(!clicked)}>Click me</Button>
        {clicked && <BarCharts />}
    </View>
}

Something like this, may not be 100% react-native compliant but you should be able to adjust it.

Upvotes: 0

Related Questions