DRAG AND DROP IN REACT (React DND)

DRAG AND DROP IN REACT

React DND

React DND

This is an example of implementing drag and drop functionality using React. This is the first example where we’ll use an external library, in this case, React DnD.

Components

This example will have two major components: Bin, a component where objects can be dropped, and Item, an item that can be dragged and dropped.

React DND, as you would expect, supports applying different functionality to different sets of data that is to be dragged and dropped. We declare the different types of item in the ItemTypes object, which is simple since in this example we only have one type of draggable item:

constItemTypes={
    ITEM:'item'};

First, we define the Item component, and declare it draggable. Because React DND, like the underlying HTML5 drag-and-drop API, supports dragging data as well as visible objects, we have to decalare what kind of data should be moved along with the component. The beginDrag function does it, and in this case we only carry the component’s name, since it’s the only data it has.

varItem=React.createClass({
  mixins:[DragDropMixin],

  statics:{
    configureDragDrop:function(register){register(ItemTypes.ITEM,{
        dragSource:{
          beginDrag:function(component){return{
              item:{
                name: component.props.name
              }};}}});}},

  render:function(){return(<li className='item'{...this.dragSourceFor(ItemTypes.ITEM)}>{this.props.name}</li>);}});

Next we define the component we can drop objects into. The Bin component has a list of dropped items in its state, and an addItem method which takes the name of an item to add to that list.

varBin=React.createClass({
  mixins:[DragDropMixin],

  getInitialState:function(){return{ items:[]};},

  addItem:function(name){
    clone =this.state.items.slice(0);
    clone.push(name);this.setState({ items: clone });},

Now we register the dropTarget function, which calls addItem when an object
is dropped into the bin:

statics:{
    configureDragDrop:function(register){register(ItemTypes.ITEM,{
        dropTarget:{
          acceptDrop:function(component, item){
            component.addItem(item.name);}}});}},

Here we have the render function. We look at the component’s drop state to see whether:

  • Nothing is happening.
  • A droppable object is being dragged.
  • A droppable object hsa been dragged over the component.

We use this to change the component’s class name, then later we’ll use CSS to style it.

We also query the component’s drop state to determine whether the text on the bin should read “Release to drop: or “Drag item here”.

render:function()
   {const dropState =this.getDropState(ItemTypes.ITEM);
var stateClass ='none';
if(dropState.isHovering){
      stateClass ='hovering';
}elseif(dropState.isDragging){
      stateClass ='dragging';
}

const dropped =this.state.items.map(function(name){
     return<li>{name}</li>;
});
return(
     <div className={'bin bin-state-'+ stateClass}
     {...this.dropTargetFor(ItemTypes.ITEM)}>
     {dropState.isHovering ?
         'Release to drop':
         'Drag item here'}
     <ul className="dropped">
          {dropped}
     </ul>
     </div>
);
}
});

Finally, we create a small container object for this example and add some example items:


var Container=React.createClass({
  render:function(){
     return(
         <div>
              <Bin/>
              <ul className='items'>
                   <Item name='Glass'/>
                   <Item name='Banana'/>
                   <Item name='Paper'/>
              </ul>
         </div>
       );
   }
});
React.render(<Container/>,
    document.body
);

Style
Now it’s time to add some CSS.
First, some general style:

body {
    margin:0;
    padding:0;
    min-height:100vh;

    font-family:'Helvetica Neue',Helvetica,Arial, sans-serif;}

Now we make the bin a big square in the middle:

.bin {
    width:300px;
    margin:35pxauto;
    padding:45px;

    color: white;
    font-size:2em;
    text-align: center;

    border-radius:5px;}

We used CSS classes to mark up the different states of the bin, so now let’s use
those to change the color of the bin to match the state:

.bin-state-none {
    background-color:#34495E;}.bin-state-dragging {
    background-color:#E98B39;}.bin-state-hovering {
    background-color:#2ECC71;}

Since we show a list of items that have been dropped inside the bin, let’s style
that:

.dropped {
    margin:20px0;
    padding:0;
}
.dropped li {
    list-style-type: none;
    font-size:0.6em;}

And finally, the items that can be dropped:

.items {
    padding:0;
    text-align: center;
}

.item {
    display:inline-block;
    padding:20px;
    margin:25px10px;

    border:2px solid #E74C3C;
}

-By
Nitin Uttarwar
Helical It Solution

Using Bootstrap Modal with ReactJS

Using Bootstrap Modal with ReactJS

Here we will be creating a reusable React-component for Bootstrap Modal.

Setup

Let’s first create a skeleton for our component. Create a file bootstrap-modal.jsx which contains the following code:

var BootstrapModal = React.createClass({
    displayName: "BootstrapModal",
    render: function () {
        return (
            <div ref="modal" className="modal fade">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button"
                                className="close">
                                <span>&times;</span>
                            </button>
                            <h4 className="modal-title">Title</h4>
                        </div>
                        <div className="modal-body">
                            Modal Body
                        </div>
                        <div className="modal-footer">
                            <button type="button"
                                className="btn btn-success">
                                OK
                            </button>
                            <button type="button"
                                className="btn btn-danger">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
});

Including Bootstrap Plugin

Now we must initiate the modal plugin when the component loads and destroy it when it unloads. Add the following code to file created in the previous step.

componentDidMount: function () {
    $(this.refs.modal.getDOMNode()).modal({
        backdrop: "static",
        show: false
    });
},
componentDidUnmount: function () {
    $(this.refs.modal.getDOMNode()).off();
}

Helpers

Now, let us write helpers for showing and hiding the modal. Add the following code to the file.

show: function () {
    $(this.refs.modal.getDOMNode()).modal("show");
},
hide: function () {
    $(this.refs.modal.getDOMNode()).modal("hide");
}

Final code

The final code must look something like this:

var BootstrapModal = React.createClass({
    displayName: "BootstrapModal",
    componentDidMount: function () {
        $(this.refs.modal.getDOMNode()).modal({
            backdrop: "static",
            show: false
        });
    },
    componentDidUnmount: function () {
        $(this.refs.modal.getDOMNode()).off();
    },
    render: function () {
        return (
            <div ref="modal" className="modal fade">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button"
                                className="close">
                                <span>&times;</span>
                            </button>
                            <h4 className="modal-title">Title</h4>
                        </div>
                        <div className="modal-body">
                            Modal Body
                        </div>
                        <div className="modal-footer">
                            <button type="button"
                                className="btn btn-success">
                                OK
                            </button>
                            <button type="button"
                                className="btn btn-danger">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    },
    show: function () {
        $(this.refs.modal.getDOMNode()).modal("show");
    },
    hide: function () {
        $(this.refs.modal.getDOMNode()).modal("hide");
    }
});

Usage

The modal component created above can be used by creating a file app.jsx with the following code:

var App = React.createClass({
    showModal: function() {
        this.refs.modal.show()
    },
    render: function() {
        <div>
            <button type="button" className="btn btn-primary" onClick={this.showModal}>Show Modal</button>
            <BootstrapModal ref="modal"/>
        </div>
    }
});

React.render(<App />, document.getElementsByTagName('body')[0]);

As you can see, we have created a simple button when clicked will show the modal.

Test Drive

Create a index.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Bootstrap Modal with ReactJS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <script src="http://fb.me/react-0.12.2.min.js"></script>
    <script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>

    <script type="text/jsx" src="path/to/bootstrap-modal.jsx"></script>
    <script type="text/jsx" src="path/to/app.jsx"></script>
</body>
</html>

When you open the file in browser (preferably via a server) and click on the button, you must see a modal.

ReactJS 101

ReactJS 101

ReactJS is a javascript library by facebook for building state aware UI. Today we’ll be looking at how to get started with it. The following examples are taken from the offical page

Setup

Download react from here and save in folder of your choice. (At the time of writing this, React version was v0.12.2). Now fire up your favourite text editor. Firstly lets make some basic html page.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>React 101</title>
    <!-- change the following paths as per your scripts location -->
    <script src="path/to/build/react.js"></script>
    <script src="path/to/build/JSXTransformer.js"></script>
</head>
<body>
    <div id="example"></div>
</body>
</html>

The JSX Syntax

React uses what the call is JSX which is transformed to vanilla javascript by JSXTransformer.js and it is like writing HTML inside JavaScript. Here’s a simple example.

React.render(<div />, mountNode);

will be compiled to

React.render(React.createElement("div"), mountNode);

Premier component

Add the following code just before the closing body tag and open it in a browser.

<script type="text/jsx">
    var HelloWorld = React.createClass({
        render: function() {
            return <div>Hello {this.props.name}</div>;
        }
    });

    React.render(<HelloWorld name="World!" />, document.getElementById("example"));
</script>

Here’s a jsfiddle

A state aware component

Lets make timer with following code

<script type="text/jsx">
    var Timer = React.createClass({
        getInitialState: function() {
            //Intialize component with state as 0 seconds
            return {secondsElapsed: 0};
        },
        tick: function() {
            //increment the timer and update the state
            this.setState({secondsElapsed: this.state.secondsElapsed + 1});
        },
        componentDidMount: function() {
            //Start the timer when the component is loaded in DOM
            this.interval = setInterval(this.tick, 1000);
        },
        componentWillUnmount: function() {
            //Clear the timer when the component is removed from DOM
            clearInterval(this.interval);
        },
        render: function() {
            return (
                <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
            );
        }
    });

    React.render(<Timer />, document.getElementById("example"));
</script>

Here’s a jsfiddle

Conclusion

This was quick look at react. I’ve just scratched the tip of the iceberg. Head to the documentation and explore for yourselves.