How to move an Image on click in React Native

10,309

There are many ways to do this, but perhaps the easiest way would be using states.

class MainBody extends Component {
    constructor(props) {
        super(props);
        this.state = {
            top: 0 // Initial value
        };
    }
  onclick = () => {
    console.log('On click works')
    this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};


  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image style={{top: this.state.top}}source={require("./img/example.png")}/>
          <View>
            <Text>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}>
            <Image source={require("./img/moveImg.png")}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
  );
  }
}
Share:
10,309
jasper
Author by

jasper

Updated on June 15, 2022

Comments

  • jasper
    jasper almost 2 years

    I've recently been learning React Native but haven't really found a way to manipulate the DOM.

    I've been trying to make it so that if I click on the TouchableHighlight my Image moves down a couple of px, but I have not managed to get it to move yet and I honestly don't know how to go from here.

    My onclick function works since it does return the log every time the button is clicked.

    As of now I have this:

    export default class MainBody extends Component {
    
      onclick = () => {
        console.log('On click works')
      };
    
      render() {
    
        return (
    
          <ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>
    
            <View >
    
              {/*i need to move this Image down!*/}
              <Image source={require("./img/example.png")}/>
              <View>
                <Text style={Style.peopleInvited}>This is text</Text>
              </View>
    
              {/*When clicked on this touchable highlight!*/}
              <TouchableHighlight onPress={this.onclick}}>
                <Image source={require('./img/moveImg.png')}/>
              </TouchableHighlight>
            </View>
    
          </ScrollView>
    }
    

    If someone could help me get past this that would be greatly appreciated. Thank you so much for your time!