Skip to content
Related Articles

Related Articles

How to change the position of the element dynamically in ReactJS ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 22 Apr, 2021

In this article we will learn to change the position of an element dynamically using ReactJS

Approach: We are going to use following steps:

  • Assume the position of our element is 0 on x-coordinate and 0 on y-coordinate.
  • Then we will add/subtract some value from x/y coordinate depending on the direction we are moving.
  • Keep all of these values in the state so that we can see the change in real-time
  • Update the coordinates in state and we will see the position of element changing.

Setting up environment and Execution:

  • Step 1: Create React App command

    npx create-react-app foldername
  • Step 2: After creating your project folder, i.e., folder name, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.


import React, { Component } from "react";
class App extends Component {
  // Create state
  state = {
    xoffset: 0,
    yoffset: 0,
    delta: 10,
  moveTitleToDown = () => {
      { yoffset: this.state.yoffset 
        + });
  moveTitleToRight = () => {
      { xoffset: this.state.xoffset 
        + });
  moveTitleToLeft = () => {
      { xoffset: this.state.xoffset 
        - });
  moveTitleToUp = () => {
      { yoffset: this.state.yoffset 
        - });
  render() {
    return (
        {/* Element to Move Dynamically */}
            position: "absolute",
            left: `${this.state.xoffset}px`,
            top: `${this.state.yoffset}px`,
        {/* Move Controls */}
        <div style={{ marginTop: "80px" }}>
          <button onClick={this.moveTitleToRight}>
            Move Title To Right
          <button onClick={this.moveTitleToDown}>
            Move Title To Down
          <button onClick={this.moveTitleToLeft}>
            Move Title To Left
          <button onClick={this.moveTitleToUp}>
            Move Title To Up
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, click on buttons to see output

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!