donzmat
donzmat

Reputation: 495

Get content from component

I'm new to react native.

My screen contains 2 buttons, each one opens the same <Modal> component, but the <View> inside it changes depending on the button clicked.

For example :

If I click the first button, a text input will be shown into the modal ; If I click the second button, a switch will be shown into the modal.

I've made a modal component (Modal.tsx) :

export default class Modal extends Component {

  public render() {
    return (
      <View style={style.modal} >
        {this.props.children}
      <View>
    )
  };
}

// Specific modal implementation with TextInput
const ModalWithTextInput = props => (
  <TextInput
    value={props.someValue}
  />
)


// Specific modal implementation with Switch
const ModalWithSwitch = props => (
  <Switch
    value={props.someValue}
  />
)

And now in my 5-button-screen (ButtonsScreen.tsx), I open the right modal depending on the button clicked :

openTextModal = () => {
   this.setState({ modalVisible: true, modalType: 'text' });
}

openSwitchModal = () => {
   this.setState({ modalVisible: true, modalType: 'switch' });
}

These functions are called with, for example, onPress={this.openTextModal}

Finally, I render the modal as this :

renderModal = (type) => {
    if (type === 'text') {
        return <ModalWithTextInput someValue="default text" />
    }

    if (type === 'switch') {
        return <ModalWithSwitch someValue={false}/>
    }
}

To be able to do something like :

<Modal
    visible={this.state.modalVisible}
    animationType={'slide'}
    onRequestClose={() => this.closeModal()}>
    <View style={style.modalContainer}>
        <View style={style.innerContainer}>
            <View>
                {this.renderModal(this.state.modalType)}
            </View>
        </View>
    </View>
</Modal>
</View>

When I try to do onPress={this.openTextModal}, the modal opens with no content. What's wrong ?

Anyone can please help ? Thanks.

Upvotes: 0

Views: 46

Answers (1)

Aaditya Thakkar
Aaditya Thakkar

Reputation: 1820

You are giving flex: 1 to modelContainer and innerContainer, but it is not getting applied on this.renderModal(this.state.modalType), because you have wrapped it with another View with no flex. Either you remove that or give it a flex: 1, modal should appear. I guess this should work fine.

<View style={style.modalContainer}>
   <View style={style.innerContainer}>
            {this.renderModal(this.state.modalType)}
    </View>
</View>

Upvotes: 1

Related Questions