2

How are you.

I would like to make component that has fixed height.

it's wrapped by ScrollView and I want this scrollview don't scroll if child height is small than fixed height.

Is that possible?

Thanks

Nomura Nori
  • 4,689
  • 8
  • 47
  • 85
  • 2
    Uhm, what about getting the child component height, comparing it to the parent fixed height and setting a boolean in your state which controls your ScrollView by its `scrollEnabled` prop? – Milore Jan 15 '19 at 22:48
  • I considered it, but I can't setState in render function, and I can only get child height in render function. – Nomura Nori Jan 15 '19 at 22:49
  • I don't think so. Take a look at this [answer](https://stackoverflow.com/a/30206471/7581249) – Milore Jan 15 '19 at 22:53
  • You are probably looking for the prop `scrollToOverflowEnabled` of `ScrollView` - this will enable the scroll only if needed. – MasterPiece Aug 08 '22 at 21:43

1 Answers1

3

You could render a normal View or a ScrollView based on some condition, consider this example:

class MyComponent extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      childHeight: 0,
      screenHeight: Dimensions.get('window').height
    }
  }
  render(){
    const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View 
    return (
      <Wrapper>
        //onLayout passes a an object with a synthetic event that has a nativeEvent prop
        //I pull off the nativeEvent prop using deconstruction so I can get the height
        <View onLayout={
          ({ nativeEvent }) => {
            this.setState({ childHeight: nativeEvent.layout.height })
          }}>
        {children}
        </View>
      </Wrapper>
    )
  }
}

This is just one implementation, you could do it however you like. Here's some more info on the onLayout prop.

If you can't or don't want to use a View then you would have to do some other sort of layout calculation. One way is by manipulating your styles and the children prop:

const myStyle = StyleSheet.create({
  childStyle: {
    height: 180 
  }
})

class MyComponent extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      childHeight: React.Children.count(props.children) * 180, 
      //get the count of how many children have been passed to your component
      //and multiple it by whatever height your children have set in their styles
      screenHeight: Dimensions.get('window').height 
  }
  render(){
    const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View
    return (
      <Wrapper>
        {children}
      </Wrapper>
    )
  }
}

If the number of children can change throughout multiple renders then I would suggest learning about the FlatList component

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65