How to render a JSX component from the function show that it dispaly on screen

Viewed 67

How to render JSX component from function to show it in the Screen.

This below is the code which is not rendering the function JSX component...

export default class HomeScreen extends Component{
  state = {
      isVisible:false
  }
  modal = ()=>{
    return(<Text>Hello world</Text>);
  }
  render(){
    return(
        <View>
          <Button onPress={this.setState({isVisible:true})}>Click me</Button>
          {this.state.isVisible?this.modal:null}
        </View>
    );
  }
}

And this Below code is working properly so i want to know what is error in first one.

export default class HomeScreen extends Component{
  state = {
      isVisible:false
  }
  modal = ()=>{
    return(<Text>Hello world</Text>);
  }
  render(){
    return(
        <View>
          <Button onPress={this.setState({isVisible:true})}>Click me</Button>
          {this.state.isVisible?<Text>Hello world</Text>:null}
        </View>
    );
  }
}

So Please tell me the error in first one what is problem due to which hello world text is not rendering through the JSX component return from the function modal.

2 Answers

Because you never called this.modal You have to call it. this.modal() It's a function that needs to be invoked. No Problem it happens.

First problem is that you dont execute the modal function.

Second you invoke the function onPress and doesn't pass a reference to a function, wrap it inside an arrow function onPress={() => this.setState({ isVisible: true })}

I will suggest to extract the Modal to a new component and include it only when state.isVisible is true

const Modal = () => <h3>Modal</h3>;

export default class HomeScreen extends Component {
  state = {
    isVisible: false
  }

  render() {
    return (
      <View>
        <Button onPress={() => this.setState({ isVisible: true })}>Click me</Button>
        {this.state.isVisible && <Modal />}
      </View>
    );
  }
}
Related