JavaScript

JavaScript

JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is a high-level, dynamic, multi-paradigm, object-oriented, prototype-based, weakly-typed language used for both client-side and server-side scripting. Its primary use is in rendering and performing manipulation of web pages. JavaScript framework is an application framework written in JavaScript where the programmers can manipulate the functions and use them for their convenience. JavaScript framework: Angular, React, Vue.js, Ember.js, Meteor, Mithril, Node.js, Polymer, Aurelia, Backbone.js, ....
Code  JS

Code JS

1653279238

How to Create a Visual Counting Animation with JavaScript

In this tutorial we're going to use JavaScript to build a visual Counting Animation.  A number will start at 0 and it will count up until it reaches the target number.

Chapters:
00:00 Intro
00:52 Getting Started     
01:34 HTML
04:02 CSS
09:23 JavaScript

πŸ“šResources
Font-Awesome: https://cdnjs.com/libraries/font-awesome 
Subscribe: https://www.youtube.com/c/WebDevelopment/featured 

#javascript 

How to Create a Visual Counting Animation with JavaScript
Web  Dev

Web Dev

1653278579

HTML, CSS & Javascript Project | Build a Number Trivia App

Number Trivia App | Javascript Project | HTML, CSS & Javascript

Create a number trivia app that displays a fact for the number the user inputs. It also consists a 'Get Random Fact' button that displays fact for random numbers.

In today’s tutorial, we will build a Number Trivia App. To create this project, we need HTML, CSS and javascript.
For this project, we will be using the Numbers API.

The project consists of a search bar. The user enters a desired number into the input field and hits the β€˜Get Fact’ button. Once the user clicks the button, a fact related to the number is displayed.

Alternatively, the user can click on the β€˜Get Random Fact’ button. Once the user clicks on this button, a random number is selected. Following this, we display a fact corresponding to that number.

We also validate the user input. If the user enters a number less than 0 or greater than 300, we display an error message. Also, if the user leaves the input field empty, we show the error message.

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. The project folder is called – Number Trivia App. Inside this folder, we have three files – index.html, style.css and script.js.

HTML:

We begin with the HTML code. First, copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Number Trivia App</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="search-container">
        <input type="num" placeholder="Number" id="num" />
        <button id="get-fact-btn">Get Fact</button>
      </div>
      <button id="ran-fact-btn">Get Random Fact</button>
      <div class="fact"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we add styling to our elements using CSS. Now copy the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #566fff;
}
.container {
  background-color: #ffffff;
  width: 95vw;
  font-size: 16px;
  max-width: 31.25em;
  padding: 3.5em 2.5em;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  border-radius: 0.6em;
  box-shadow: 0 1.2em 3em rgba(0, 4, 52, 0.2);
}
.search-container {
  display: flex;
  justify-content: space-between;
}
.container input,
.container button {
  font-size: 1.25em;
  outline: none;
  border: none;
  border-radius: 0.4em;
}
.container input {
  width: 40%;
  border: 1px solid #bdbdbf;
  padding: 0.6em;
}
.container button {
  width: 55%;
  background-color: #566fff;
  color: #ffffff;
  font-weight: 500;
  padding: 0.7em;
  cursor: pointer;
}
#ran-fact-btn {
  width: 100%;
  margin-top: 1em;
}
.fact {
  background-color: #ffffff;
  box-shadow: 0 0 1.2em rgba(0, 4, 52, 0.1);
  margin: 3em auto 0 auto;
  padding: 2.8em 1.8em;
  border-radius: 0.6em;
  border: none;
  border-bottom: 0.6em solid #566fff;
  display: none;
}
.fact h2 {
  font-size: 2.8em;
  color: #181a34;
}
.fact p {
  font-size: 1.15em;
  font-weight: 400;
  color: #50526b;
  line-height: 1.8em;
  text-align: justify;
  margin-top: 0.8em;
}
p.msg {
  text-align: center;
  font-weight: 500;
  color: #181a34;
}

Javascript:

Finally, we add functionality to this project using Javascript. Once again, copy the code below and paste it into your script file.

let getFactBtn = document.getElementById("get-fact-btn");
let ranFactBtn = document.getElementById("ran-fact-btn");
let fact = document.querySelector(".fact");
let url = "http://numbersapi.com/";

let fetchFact = (num) => {
  let finalUrl = url + num;
  fetch(finalUrl)
    .then((resp) => resp.text())
    .then((data) => {
      fact.style.display = "block";
      fact.innerHTML = `<h2>${num}</h2>
      <p>${data}</p>`;
      document.querySelector(".container").append(fact);
    });
};
let getFact = () => {
  let num = document.getElementById("num").value;
  //Check if input number is not empty
  //If not empty
  if (num) {
    //Check if number lies between 0 and 300
    //if Yes fetch the fact
    if (num >= 0 && num <= 300) {
      fetchFact(num);
    }
    //If number is less than 0 or greater than 300 display error message.
    else {
      fact.style.display = "block";
      fact.innerHTML = `<p class="msg"> Please enter a number between 0 to 300.</p>`;
    }
  }
  //If input number is empty display error message
  else {
    fact.style.display = "block";
    fact.innerHTML = `<p class="msg">The input field cannot be empty</p>`;
  }
};

let getRandomFact = () => {
  //Random number between 0 to 300
  let num = Math.floor(Math.random() * 301);
  fetchFact(num);
};

getFactBtn.addEventListener("click", getFact);
ranFactBtn.addEventListener("click", getRandomFact);
window.addEventListener("load", getRandomFact);

If you face any issues while creating this code, you can download the source code by clicking on the β€˜Download Code’ button below. Also, feel free to drop your suggestions and feedback in the comments below.

API Used:
http://numbersapi.com/ 

πŸ“ Download Source Code : 
https://www.codingartistweb.com

#html #javascript #css 

HTML, CSS & Javascript Project | Build a Number Trivia App
Leonard  Paucek

Leonard Paucek

1653278400

Sortable: A JavaScript Library for Reorderable Drag and Drop Lists

Sortable    

Sortable is a JavaScript library for reorderable drag-and-drop lists.

Demo: http://sortablejs.github.io/Sortable/

Features

  • Supports touch devices and modern browsers (including IE9)
  • Can drag from one list to another or within the same list
  • CSS animation when moving items
  • Supports drag handles and selectable text (better than voidberg's html5sortable)
  • Smart auto-scrolling
  • Advanced swap detection
  • Smooth animations
  • Multi-drag support
  • Support for CSS transforms
  • Built using native HTML5 drag and drop API
  • Supports
  • Supports any CSS library, e.g. Bootstrap
  • Simple API
  • Support for plugins
  • CDN
  • No jQuery required (but there is support)
  • Typescript definitions at @types/sortablejs


 

Articles


 

Getting Started

Install with NPM:

$ npm install sortablejs --save

Install with Bower:

$ bower install --save sortablejs

Import into your project:

// Default SortableJS
import Sortable from 'sortablejs';

// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';

// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';

Cherrypick plugins:

// Cherrypick extra plugins
import Sortable, { MultiDrag, Swap } from 'sortablejs';

Sortable.mount(new MultiDrag(), new Swap());


// Cherrypick default plugins
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';

Sortable.mount(new AutoScroll());

Usage

<ul id="items">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
var el = document.getElementById('items');
var sortable = Sortable.create(el);

You can use any element for the list and its elements, not just ul/li. Here is an example with divs.


Options

var sortable = new Sortable(el, {
    group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
    sort: true,  // sorting inside list
    delay: 0, // time in milliseconds to define when the sorting should start
    delayOnTouchOnly: false, // only delay if user is using touch
    touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
    disabled: false, // Disables the sortable if set to true.
    store: null,  // @see Store
    animation: 150,  // ms, animation speed moving items when sorting, `0` β€” without animation
    easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
    handle: ".my-handle",  // Drag handle selector within list items
    filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
    preventOnFilter: true, // Call `event.preventDefault()` when triggered `filter`
    draggable: ".item",  // Specifies which items inside the element should be draggable

    dataIdAttr: 'data-id', // HTML attribute that is used by the `toArray()` method

    ghostClass: "sortable-ghost",  // Class name for the drop placeholder
    chosenClass: "sortable-chosen",  // Class name for the chosen item
    dragClass: "sortable-drag",  // Class name for the dragging item

    swapThreshold: 1, // Threshold of the swap zone
    invertSwap: false, // Will always use inverted swap zone if set to true
    invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
    direction: 'horizontal', // Direction of Sortable (will be detected automatically if not given)

    forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

    fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
    fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
    fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

    dragoverBubble: false,
    removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
    emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


    setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
        dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
    },

    // Element is chosen
    onChoose: function (/**Event*/evt) {
        evt.oldIndex;  // element index within parent
    },

    // Element is unchosen
    onUnchoose: function(/**Event*/evt) {
        // same properties as onEnd
    },

    // Element dragging started
    onStart: function (/**Event*/evt) {
        evt.oldIndex;  // element index within parent
    },

    // Element dragging ended
    onEnd: function (/**Event*/evt) {
        var itemEl = evt.item;  // dragged HTMLElement
        evt.to;    // target list
        evt.from;  // previous list
        evt.oldIndex;  // element's old index within old parent
        evt.newIndex;  // element's new index within new parent
        evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
        evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
        evt.clone // the clone element
        evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
    },

    // Element is dropped into the list from another list
    onAdd: function (/**Event*/evt) {
        // same properties as onEnd
    },

    // Changed sorting within list
    onUpdate: function (/**Event*/evt) {
        // same properties as onEnd
    },

    // Called by any change to the list (add / update / remove)
    onSort: function (/**Event*/evt) {
        // same properties as onEnd
    },

    // Element is removed from the list into another list
    onRemove: function (/**Event*/evt) {
        // same properties as onEnd
    },

    // Attempt to drag a filtered element
    onFilter: function (/**Event*/evt) {
        var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
    },

    // Event when you move an item in the list or between lists
    onMove: function (/**Event*/evt, /**Event*/originalEvent) {
        // Example: https://jsbin.com/nawahef/edit?js,output
        evt.dragged; // dragged HTMLElement
        evt.draggedRect; // DOMRect {left, top, right, bottom}
        evt.related; // HTMLElement on which have guided
        evt.relatedRect; // DOMRect
        evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
        originalEvent.clientY; // mouse position
        // return false; β€” for cancel
        // return -1; β€” insert before target
        // return 1; β€” insert after target
        // return true; β€” keep default insertion point based on the direction
        // return void; β€” keep default insertion point based on the direction
    },

    // Called when creating a clone of element
    onClone: function (/**Event*/evt) {
        var origEl = evt.item;
        var cloneEl = evt.clone;
    },

    // Called when dragging element changes position
    onChange: function(/**Event*/evt) {
        evt.newIndex // most likely why this event is used is to get the dragging element's current index
        // same properties as onEnd
    }
});

group option

To drag elements from one list into another, both lists must have the same group value. You can also define whether lists can give away, give and keep a copy (clone), and receive elements.

  • name: String β€” group name
  • pull: true|false|["foo", "bar"]|'clone'|function β€” ability to move from the list. clone β€” copy the item, rather than move. Or an array of group names which the elements may be put in. Defaults to true.
  • put: true|false|["baz", "qux"]|function β€” whether elements can be added from other lists, or an array of group names from which elements can be added.
  • revertClone: boolean β€” revert cloned element to initial position after moving to a another list.

Demo:


sort option

Allow sorting inside list.

Demo: https://jsbin.com/jayedig/edit?js,output


delay option

Time in milliseconds to define when the sorting should start. Unfortunately, due to browser restrictions, delaying is not possible on IE or Edge with native drag & drop.

Demo: https://jsbin.com/zosiwah/edit?js,output


delayOnTouchOnly option

Whether or not the delay should be applied only if the user is using touch (eg. on a mobile device). No delay will be applied in any other case. Defaults to false.


swapThreshold option

Percentage of the target that the swap zone will take up, as a float between 0 and 1.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertSwap option

Set to true to set the swap zone to the sides of the target, for the effect of sorting "in between" items.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertedSwapThreshold option

Percentage of the target that the inverted swap zone will take up, as a float between 0 and 1. If not given, will default to swapThreshold.

Read more


direction option

Direction that the Sortable should sort in. Can be set to 'vertical', 'horizontal', or a function, which will be called whenever a target is dragged over. Must return 'vertical' or 'horizontal'.

Read more

Example of direction detection for vertical list that includes full column and half column elements:

Sortable.create(el, {
    direction: function(evt, target, dragEl) {
        if (target !== null && target.className.includes('half-column') && dragEl.className.includes('half-column')) {
            return 'horizontal';
        }
        return 'vertical';
    }
});

touchStartThreshold option

This option is similar to fallbackTolerance option.

When the delay option is set, some phones with very sensitive touch displays like the Samsung Galaxy S8 will fire unwanted touchmove events even when your finger is not moving, resulting in the sort not triggering.

This option sets the minimum pointer movement that must occur before the delayed sorting is cancelled.

Values between 3 to 5 are good.


disabled options

Disables the sortable if set to true.

Demo: https://jsbin.com/sewokud/edit?js,output

var sortable = Sortable.create(list);

document.getElementById("switcher").onclick = function () {
    var state = sortable.option("disabled"); // get

    sortable.option("disabled", !state); // set
};

handle option

To make list items draggable, Sortable disables text selection by the user. That's not always desirable. To allow text selection, define a drag handler, which is an area of every list element that allows it to be dragged around.

Demo: https://jsbin.com/numakuh/edit?html,js,output

Sortable.create(el, {
    handle: ".my-handle"
});
<ul>
    <li><span class="my-handle">::</span> list item text one
    <li><span class="my-handle">::</span> list item text two
</ul>
.my-handle {
    cursor: move;
    cursor: -webkit-grabbing;
}

filter option

Sortable.create(list, {
    filter: ".js-remove, .js-edit",
    onFilter: function (evt) {
        var item = evt.item,
            ctrl = evt.target;

        if (Sortable.utils.is(ctrl, ".js-remove")) {  // Click on remove button
            item.parentNode.removeChild(item); // remove sortable item
        }
        else if (Sortable.utils.is(ctrl, ".js-edit")) {  // Click on edit link
            // ...
        }
    }
})

ghostClass option

Class name for the drop placeholder (default sortable-ghost).

Demo: https://jsbin.com/henuyiw/edit?css,js,output

.ghost {
  opacity: 0.4;
}
Sortable.create(list, {
  ghostClass: "ghost"
});

chosenClass option

Class name for the chosen item (default sortable-chosen).

Demo: https://jsbin.com/hoqufox/edit?css,js,output

.chosen {
  color: #fff;
  background-color: #c00;
}
Sortable.create(list, {
  delay: 500,
  chosenClass: "chosen"
});

forceFallback option

If set to true, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser. This gives us the possibility to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.

On top of that, the Fallback always generates a copy of that DOM Element and appends the class fallbackClass defined in the options. This behaviour controls the look of this 'dragged' Element.

Demo: https://jsbin.com/sibiput/edit?html,css,js,output


fallbackTolerance option

Emulates the native drag threshold. Specify in pixels how far the mouse should move before it's considered as a drag. Useful if the items are also clickable like in a list of links.

When the user clicks inside a sortable element, it's not uncommon for your hand to move a little between the time you press and the time you release. Dragging only starts if you move the pointer past a certain tolerance, so that you don't accidentally start dragging every time you click.

3 to 5 are probably good values.


dragoverBubble option

If set to true, the dragover event will bubble to parent sortables. Works on both fallback and native dragover event. By default, it is false, but Sortable will only stop bubbling the event once the element has been inserted into a parent Sortable, or can be inserted into a parent Sortable, but isn't at that specific time (due to animation, etc).

Since 1.8.0, you will probably want to leave this option as false. Before 1.8.0, it may need to be true for nested sortables to work.


removeCloneOnHide option

If set to false, the clone is hidden by having it's CSS display property set to none. By default, this option is true, meaning Sortable will remove the cloned element from the DOM when it is supposed to be hidden.


emptyInsertThreshold option

The distance (in pixels) the mouse must be from an empty sortable while dragging for the drag element to be inserted into that sortable. Defaults to 5. Set to 0 to disable this feature.

Demo: https://jsbin.com/becavoj/edit?js,output

An alternative to this option would be to set a padding on your list when it is empty.

For example:

ul:empty {
  padding-bottom: 20px;
}

Warning: For :empty to work, it must have no node inside (even text one).

Demo: https://jsbin.com/yunakeg/edit?html,css,js,output


Event object (demo)

  • to:HTMLElement β€” list, in which moved element
  • from:HTMLElement β€” previous list
  • item:HTMLElement β€” dragged element
  • clone:HTMLElement
  • oldIndex:Number|undefined β€” old index within parent
  • newIndex:Number|undefined β€” new index within parent
  • oldDraggableIndex: Number|undefined β€” old index within parent, only counting draggable elements
  • newDraggableIndex: Number|undefined β€” new index within parent, only counting draggable elements
  • pullMode:String|Boolean|undefined β€” Pull mode if dragging into another sortable ("clone", true, or false), otherwise undefined

move event object

  • to:HTMLElement
  • from:HTMLElement
  • dragged:HTMLElement
  • draggedRect:DOMRect
  • related:HTMLElement β€” element on which have guided
  • relatedRect:DOMRect
  • willInsertAfter:Boolean β€” true if will element be inserted after target (or false if before)

Methods

option(name:String[, value:*]):*

Get or set the option.

closest(el:HTMLElement[, selector:String]):HTMLElement|null

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

toArray():String[]

Serializes the sortable's item data-id's (dataIdAttr option) into an array of string.

sort(order:String[], useAnimation:Boolean)

Sorts the elements according to the array.

var order = sortable.toArray();
sortable.sort(order.reverse(), true); // apply

save()

Save the current sorting (see store)

destroy()

Removes the sortable functionality completely.


 

Store

Saving and restoring of the sort.

<ul>
    <li data-id="1">order</li>
    <li data-id="2">save</li>
    <li data-id="3">restore</li>
</ul>
Sortable.create(el, {
    group: "localStorage-example",
    store: {
        /**
         * Get the order of elements. Called once during initialization.
         * @param   {Sortable}  sortable
         * @returns {Array}
         */
        get: function (sortable) {
            var order = localStorage.getItem(sortable.options.group.name);
            return order ? order.split('|') : [];
        },

        /**
         * Save the order of elements. Called onEnd (when the item is dropped).
         * @param {Sortable}  sortable
         */
        set: function (sortable) {
            var order = sortable.toArray();
            localStorage.setItem(sortable.options.group.name, order.join('|'));
        }
    }
})

 

Bootstrap

Demo: https://jsbin.com/visimub/edit?html,js,output

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>


<!-- Latest Sortable -->
<script src="http://SortableJS.github.io/Sortable/Sortable.js"></script>


<!-- Simple List -->
<ul id="simpleList" class="list-group">
    <li class="list-group-item">This is <a href="http://SortableJS.github.io/Sortable/">Sortable</a></li>
    <li class="list-group-item">It works with Bootstrap...</li>
    <li class="list-group-item">...out of the box.</li>
    <li class="list-group-item">It has support for touch devices.</li>
    <li class="list-group-item">Just drag some elements around.</li>
</ul>

<script>
    // Simple list
    Sortable.create(simpleList, { /* options */ });
</script>

Static methods & properties

Sortable.create(el:HTMLElement[, options:Object]):Sortable

Create new instance.


Sortable.active:Sortable

The active Sortable instance.


Sortable.dragged:HTMLElement

The element being dragged.


Sortable.ghost:HTMLElement

The ghost element.


Sortable.clone:HTMLElement

The clone element.


Sortable.get(element:HTMLElement):Sortable

Get the Sortable instance on an element.


Sortable.mount(plugin:...SortablePlugin|SortablePlugin[])

Mounts a plugin to Sortable.


Sortable.utils

  • on(el:HTMLElement, event:String, fn:Function) β€” attach an event handler function
  • off(el:HTMLElement, event:String, fn:Function) β€” remove an event handler
  • css(el:HTMLElement):Object β€” get the values of all the CSS properties
  • css(el:HTMLElement, prop:String):Mixed β€” get the value of style properties
  • css(el:HTMLElement, prop:String, value:String) β€” set one CSS properties
  • css(el:HTMLElement, props:Object) β€” set more CSS properties
  • find(ctx:HTMLElement, tagName:String[, iterator:Function]):Array β€” get elements by tag name
  • bind(ctx:Mixed, fn:Function):Function β€” Takes a function and returns a new one that will always have a particular context
  • is(el:HTMLElement, selector:String):Boolean β€” check the current matched set of elements against a selector
  • closest(el:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Null β€” for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
  • clone(el:HTMLElement):HTMLElement β€” create a deep copy of the set of matched elements
  • toggleClass(el:HTMLElement, name:String, state:Boolean) β€” add or remove one classes from each element
  • detectDirection(el:HTMLElement):String β€” automatically detect the direction of the element as either 'vertical' or 'horizontal'

Plugins

Extra Plugins (included in complete versions)

Default Plugins (included in default versions)


 

CDN

<!-- jsDelivr :: Sortable :: Latest (https://www.jsdelivr.com/package/npm/sortablejs) -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

Contributing (Issue/PR)

Please, read this.


Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute]. 

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

MIT LICENSE

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Author: SortableJS
Source Code: https://github.com/SortableJS/Sortable
License: MIT license

#react-native #react #javascript 

Sortable: A JavaScript Library for Reorderable Drag and Drop Lists

μžλ°”μŠ€ν¬λ¦½νŠΈ 쒅말각?! HTMLμ—μ„œ 파이썬 μ‹€ν–‰ν•˜λŠ” PyScript λ“±μž₯!

μžλ°”μŠ€ν¬λ¦½νŠΈ 쒅말각?! HTMLμ—μ„œ 파이썬 μ‹€ν–‰ν•˜λŠ” PyScript λ“±μž₯!

End of JavaScript? Run Python with HTML

μš”μ¦˜ μ™„μ Ό λ‚œλ¦¬λ‚œ '파이슀크립트' PyScript 10λΆ„ μ„€λͺ…!
μž˜κ°€~ μžλ°”μŠ€ν¬λ¦½νŠΈ~ μ΄λ•ŒκΉŒμ§€ κ³ λ§ˆμ› κ³ . λ‹€μ‹  λ³΄μ§€λ§μž (!?!?)
 

#pyscript #anaconda #python #javascript #html
 

μžλ°”μŠ€ν¬λ¦½νŠΈ 쒅말각?! HTMLμ—μ„œ 파이썬 μ‹€ν–‰ν•˜λŠ” PyScript λ“±μž₯!
Dexter  Goodwin

Dexter Goodwin

1653274920

FastImage, Performant React Native Image Component

🚩 FastImage

Performant React Native image component.  

 
FastImage example app.

React Native's Image component handles image caching like browsers for the most part. If the server is returning proper cache control headers for images you'll generally get the sort of built in caching behavior you'd have in a browser. Even so many people have noticed:

  • Flickering.
  • Cache misses.
  • Low performance loading from cache.
  • Low performance in general.

FastImage is an Image replacement that solves these issues. FastImage is a wrapper around SDWebImage (iOS) and Glide (Android).

Features

  •  Aggressively cache images.
  •  Add authorization headers.
  •  Prioritize images.
  •  Preload images.
  •  GIF support.
  •  Border radius.

Usage

Note: You must be using React Native 0.60.0 or higher to use the most recent version of react-native-fast-image.

yarn add react-native-fast-image
cd ios && pod install
import FastImage from 'react-native-fast-image'

const YourImage = () => (
    <FastImage
        style={{ width: 200, height: 200 }}
        source={{
            uri: 'https://unsplash.it/400/400?image=1',
            headers: { Authorization: 'someAuthToken' },
            priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
    />
)

Are you using Glide already using an AppGlideModule?

Are you using Proguard?

If you use Proguard you will need to add these lines to android/app/proguard-rules.pro:

-keep public class com.dylanvann.fastimage.* {*;}
-keep public class com.dylanvann.fastimage.** {*;}
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

Properties

source?: object

Source for the remote image to load.


source.uri?: string

Remote url to load the image from. e.g. 'https://facebook.github.io/react/img/logo_og.png'.


source.headers?: object

Headers to load the image with. e.g. { Authorization: 'someAuthToken' }.


source.priority?: enum

  • FastImage.priority.low - Low Priority.
  • FastImage.priority.normal (Default) - Normal Priority.
  • FastImage.priority.high - High Priority.

source.cache?: enum

  • FastImage.cacheControl.immutable - (Default) - Only updates if url changes.
  • FastImage.cacheControl.web - Use headers and follow normal caching procedures.
  • FastImage.cacheControl.cacheOnly - Only show images from cache, do not make any network requests.

resizeMode?: enum

  • FastImage.resizeMode.contain - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.cover (Default) - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.stretch - Scale width and height independently, This may change the aspect ratio of the src.
  • FastImage.resizeMode.center - Do not scale the image, keep centered.

onLoadStart?: () => void

Called when the image starts to load.


onProgress?: (event) => void

Called when the image is loading.

e.g. onProgress={e => console.log(e.nativeEvent.loaded / e.nativeEvent.total)}


onLoad?: (event) => void

Called on a successful image fetch. Called with the width and height of the loaded image.

e.g. onLoad={e => console.log(e.nativeEvent.width, e.nativeEvent.height)}


onError?: () => void

Called on an image fetching error.


onLoadEnd?: () => void

Called when the image finishes loading, whether it was successful or an error.


style

A React Native style. Supports using borderRadius.


fallback: boolean

If true will fallback to using Image. In this case the image will still be styled and laid out the same way as FastImage.


tintColor?: number | string

If supplied, changes the color of all the non-transparent pixels to the given color.

Static Methods

FastImage.preload: (source[]) => void

Preload images to display later. e.g.

FastImage.preload([
    {
        uri: 'https://facebook.github.io/react/img/logo_og.png',
        headers: { Authorization: 'someAuthToken' },
    },
    {
        uri: 'https://facebook.github.io/react/img/logo_og.png',
        headers: { Authorization: 'someAuthToken' },
    },
])

FastImage.clearMemoryCache: () => Promise<void>

Clear all images from memory cache.

FastImage.clearDiskCache: () => Promise<void>

Clear all images from disk cache.

Troubleshooting

If you have any problems using this library try the steps in troubleshooting and see if they fix it.

Development

Follow these instructions to get the example app running.

Supported React Native Versions

This project only aims to support the latest version of React Native.
This simplifies the development and the testing of the project.

If you require new features or bug fixes for older versions you can fork this project.

Credits

The idea for this modules came from vovkasm's react-native-web-image package. It also uses Glide and SDWebImage, but didn't have some features I needed (priority, headers).

Thanks to @mobinni for helping with the conceptualization

Author: DylanVann
Source Code: https://github.com/DylanVann/react-native-fast-image 
License: MIT license

#react #javascript #typescript #image 

FastImage, Performant React Native Image Component

How to Create Login & Register Using Angular Reactive Forms

In this video we learn How to create Login & Register using Angular Reactive Forms

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time.

Code link: https://drive.google.com/file/d/1r8vNd2IZ8frwnfFV6AzFf9DZpMsl3fAT/view?usp=sharing 

Subscribe: https://www.youtube.com/c/NSCODE/featured 

#angular #javascript 

How to Create Login & Register Using Angular Reactive Forms
Dexter  Goodwin

Dexter Goodwin

1653271080

React-native-gifted-chat: The Most Complete Chat UI for React Native

 πŸ’¬ Gifted Chat

The most complete chat UI for React Native & Web

  react-native-gifted-chat     

Features

  • πŸŽ‰ react-native-webable (since 0.10.0) web configuration
  • Write with TypeScript (since 0.8.0)
  • Fully customizable components
  • Composer actions (to attach photos, etc.)
  • Load earlier messages
  • Copy messages to clipboard
  • Touchable links using react-native-parsed-text
  • Avatar as user's initials
  • Localized dates
  • Multi-line TextInput
  • InputToolbar avoiding keyboard
  • Redux support
  • System message
  • Quick Reply messages (bot)
  • Typing indicator react-native-typing-animation

Dependency

  • Use version 0.2.x for RN >= 0.44.0
  • Use version 0.1.x for RN >= 0.40.0
  • Use version 0.0.10 for RN < 0.40.0

Installation

  • Using npm: npm install react-native-gifted-chat --save
  • Using Yarn: yarn add react-native-gifted-chat

react-native-video and expo-av

  • Both dependencies are removed since 0.11.0.
  • You still be able to provide a video but you need to provide renderMessageVideo prop.

You have a question?

  1. Please check this readme and may find a response
  2. Please ask on StackOverflow first: https://stackoverflow.com/questions/tagged/react-native-gifted-chat
  3. Find response on existing issues
  4. Try to keep issues for issues

Example

import React, { useState, useCallback, useEffect } from 'react'
import { GiftedChat } from 'react-native-gifted-chat'

export function Example() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    setMessages([
      {
        _id: 1,
        text: 'Hello developer',
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'React Native',
          avatar: 'https://placeimg.com/140/140/any',
        },
      },
    ])
  }, [])

  const onSend = useCallback((messages = []) => {
    setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
  }, [])

  return (
    <GiftedChat
      messages={messages}
      onSend={messages => onSend(messages)}
      user={{
        _id: 1,
      }}
    />
  )
}

Advanced example

See App.tsx for a working demo!

"Slack" example

See the files in example-slack-message for an example of how to override the default UI to make something that looks more like Slack -- with usernames displayed and all messages on the left.

Message object

e.g. Chat Message

export interface IMessage {
  _id: string | number
  text: string
  createdAt: Date | number
  user: User
  image?: string
  video?: string
  audio?: string
  system?: boolean
  sent?: boolean
  received?: boolean
  pending?: boolean
  quickReplies?: QuickReplies
}
{
  _id: 1,
  text: 'My message',
  createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
  user: {
    _id: 2,
    name: 'React Native',
    avatar: 'https://facebook.github.io/react/img/logo_og.png',
  },
  image: 'https://facebook.github.io/react/img/logo_og.png',
  // You can also add a video prop:
  video: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
  // Mark the message as sent, using one tick
  sent: true,
  // Mark the message as received, using two tick
  received: true,
  // Mark the message as pending with a clock loader
  pending: true,
  // Any additional custom parameters are passed through
}

e.g. System Message

{
  _id: 1,
  text: 'This is a system message',
  createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
  system: true,
  // Any additional custom parameters are passed through
}

e.g. Chat Message with Quick Reply options

See PR #1211

interface Reply {
  title: string
  value: string
  messageId?: any
}

interface QuickReplies {
  type: 'radio' | 'checkbox'
  values: Reply[]
  keepIt?: boolean
}
  {
    _id: 1,
    text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
    createdAt: new Date(),
    quickReplies: {
      type: 'radio', // or 'checkbox',
      keepIt: true,
      values: [
        {
          title: 'πŸ˜‹ Yes',
          value: 'yes',
        },
        {
          title: 'πŸ“· Yes, let me show you with a picture!',
          value: 'yes_picture',
        },
        {
          title: '😞 Nope. What?',
          value: 'no',
        },
      ],
    },
    user: {
      _id: 2,
      name: 'React Native',
    },
  },
  {
    _id: 2,
    text: 'This is a quick reply. Do you love Gifted Chat? (checkbox)',
    createdAt: new Date(),
    quickReplies: {
      type: 'checkbox', // or 'radio',
      values: [
        {
          title: 'Yes',
          value: 'yes',
        },
        {
          title: 'Yes, let me show you with a picture!',
          value: 'yes_picture',
        },
        {
          title: 'Nope. What?',
          value: 'no',
        },
      ],
    },
    user: {
      _id: 2,
      name: 'React Native',
    },
  }

Props

  • messages (Array) - Messages to display
  • isTyping (Bool) - Typing Indicator state; default false. If you userenderFooter it will override this.
  • text (String) - Input text; default is undefined, but if specified, it will override GiftedChat's internal state (e.g. for redux; see notes below)
  • placeholder (String) - Placeholder when text is empty; default is 'Type a message...'
  • messageIdGenerator (Function) - Generate an id for new messages. Defaults to UUID v4, generated by uuid
  • user (Object) - User sending the messages: { _id, name, avatar }
  • onSend (Function) - Callback when sending a message
  • alwaysShowSend (Bool) - Always show send button in input text composer; default false, show only when text input is not empty
  • locale (String) - Locale to localize the dates. You need first to import the locale you need (ie. require('dayjs/locale/de') or import 'dayjs/locale/fr')
  • timeFormat (String) - Format to use for rendering times; default is 'LT' (see Day.js Format)
  • dateFormat (String) - Format to use for rendering dates; default is 'll' (see Day.js Format)
  • loadEarlier (Bool) - Enables the "load earlier messages" button, required for infiniteScroll
  • isKeyboardInternallyHandled (Bool) - Determine whether to handle keyboard awareness inside the plugin. If you have your own keyboard handling outside the plugin set this to false; default is true
  • onLoadEarlier (Function) - Callback when loading earlier messages
  • isLoadingEarlier (Bool) - Display an ActivityIndicator when loading earlier messages
  • renderLoading (Function) - Render a loading view when initializing
  • renderLoadEarlier (Function) - Custom "Load earlier messages" button
  • renderAvatar (Function) - Custom message avatar; set to null to not render any avatar for the message
  • showUserAvatar (Bool) - Whether to render an avatar for the current user; default is false, only show avatars for other users
  • showAvatarForEveryMessage (Bool) - When false, avatars will only be displayed when a consecutive message is from the same user on the same day; default is false
  • onPressAvatar (Function(user)) - Callback when a message avatar is tapped
  • onLongPressAvatar (Function(user)) - Callback when a message avatar is long-pressed
  • renderAvatarOnTop (Bool) - Render the message avatar at the top of consecutive messages, rather than the bottom; default is false
  • renderBubble (Function) - Custom message bubble
  • renderTicks (Function(message)) - Custom ticks indicator to display message status
  • renderSystemMessage (Function) - Custom system message
  • onPress (Function(context, message)) - Callback when a message bubble is pressed
  • onLongPress (Function(context, message)) - Callback when a message bubble is long-pressed; default is to show an ActionSheet with "Copy Text" (see example using showActionSheetWithOptions())
  • inverted (Bool) - Reverses display order of messages; default is true
  • renderUsernameOnMessage (Bool) - Indicate whether to show the user's username inside the message bubble; default is false
  • renderMessage (Function) - Custom message container
  • renderMessageText (Function) - Custom message text
  • renderMessageImage (Function) - Custom message image
  • renderMessageVideo (Function) - Custom message video
  • imageProps (Object) - Extra props to be passed to the <Image> component created by the default renderMessageImage
  • videoProps (Object) - Extra props to be passed to the video component created by the required renderMessageVideo
  • lightboxProps (Object) - Extra props to be passed to the MessageImage's Lightbox
  • isCustomViewBottom (Bool) - Determine whether renderCustomView is displayed before or after the text, image and video views; default is false
  • renderCustomView (Function) - Custom view inside the bubble
  • renderDay (Function) - Custom day above a message
  • renderTime (Function) - Custom time inside a message
  • renderFooter (Function) - Custom footer component on the ListView, e.g. 'User is typing...'; see App.tsx for an example. Overrides default typing indicator that triggers when isTyping is true.
  • renderChatEmpty (Function) - Custom component to render in the ListView when messages are empty
  • renderChatFooter (Function) - Custom component to render below the MessageContainer (separate from the ListView)
  • renderInputToolbar (Function) - Custom message composer container
  • renderComposer (Function) - Custom text input message composer
  • renderActions (Function) - Custom action button on the left of the message composer
  • renderSend (Function) - Custom send button; you can pass children to the original Send component quite easily, for example, to use a custom icon (example)
  • renderAccessory (Function) - Custom second line of actions below the message composer
  • onPressActionButton (Function) - Callback when the Action button is pressed (if set, the default actionSheet will not be used)
  • bottomOffset (Integer) - Distance of the chat from the bottom of the screen (e.g. useful if you display a tab bar)
  • minInputToolbarHeight (Integer) - Minimum height of the input toolbar; default is 44
  • listViewProps (Object) - Extra props to be passed to the messages <ListView>; some props can't be overridden, see the code in MessageContainer.render() for details
  • textInputProps (Object) - Extra props to be passed to the <TextInput>
  • textInputStyle (Object) - Custom style to be passed to the <TextInput>
  • multiline (Bool) - Indicates whether to allow the <TextInput> to be multiple lines or not; default true.
  • keyboardShouldPersistTaps (Enum) - Determines whether the keyboard should stay visible after a tap; see <ScrollView> docs
  • onInputTextChanged (Function) - Callback when the input text changes
  • maxInputLength (Integer) - Max message composer TextInput length
  • parsePatterns (Function) - Custom parse patterns for react-native-parsed-text used to linking message content (like URLs and phone numbers), e.g.:
 <GiftedChat
   parsePatterns={(linkStyle) => [
     { type: 'phone', style: linkStyle, onPress: this.onPressPhoneNumber },
     { pattern: /#(\w+)/, style: { ...linkStyle, styles.hashtag }, onPress: this.onPressHashtag },
   ]}
 />
  • extraData (Object) - Extra props for re-rendering FlatList on demand. This will be useful for rendering footer etc.
  • minComposerHeight (Object) - Custom min-height of the composer.
  • maxComposerHeight (Object) - Custom max height of the composer.
  • scrollToBottom (Bool) - Enables the scroll to bottom Component (Default is false)
  • scrollToBottomComponent (Function) - Custom Scroll To Bottom Component container
  • scrollToBottomOffset (Integer) - Custom Height Offset upon which to begin showing Scroll To Bottom Component (Default is 200)
  • scrollToBottomStyle (Object) - Custom style for Bottom Component container
  • alignTop (Boolean) Controls whether or not the message bubbles appear at the top of the chat (Default is false - bubbles align to bottom)
  • onQuickReply (Function) - Callback when sending a quick reply (to backend server)
  • renderQuickReplies (Function) - Custom all quick reply view
  • quickReplyStyle (StyleProp) - Custom quick reply view style
  • renderQuickReplySend (Function) - Custom quick reply send view
  • shouldUpdateMessage (Function) - Lets the message component know when to update outside of normal cases.
  • infiniteScroll (Bool) - infinite scroll up when reach the top of messages container, automatically call onLoadEarlier function if exist (not yet supported for the web). You need to add loadEarlier prop too.

Imperative methods

  • focusTextInput() - Open the keyboard and focus the text input box

Notes for Redux

The messages prop should work out-of-the-box with Redux. In most cases, this is all you need.

If you decide to specify a text prop, GiftedChat will no longer manage its own internal text state and will defer entirely to your prop. This is great for using a tool like Redux, but there's one extra step you'll need to take: simply implement onInputTextChanged to receive typing events and reset events (e.g. to clear the text onSend):

<GiftedChat
  text={customText}
  onInputTextChanged={text => this.setCustomText(text)}
  /* ... */
/>

Notes for Android

If you are using Create React Native App / Expo, no Android specific installation steps are required -- you can skip this section. Otherwise, we recommend modifying your project configuration as follows.

Make sure you have android:windowSoftInputMode="adjustResize" in your AndroidManifest.xml:

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:windowSoftInputMode="adjustResize"
  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">

For Expo, there are at least 2 solutions to fix it:

  • Append KeyboardAvoidingView after GiftedChat. This should only be done for Android, as KeyboardAvoidingView may conflict with the iOS keyboard avoidance already built into GiftedChat, e.g.:
<View style={{ flex: 1 }}>
   <GiftedChat />
   {
      Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />
   }
</View>

If you use React Navigation, additional handling may be required to account for navigation headers and tabs. KeyboardAvoidingView's keyboardVerticalOffset property can be set to the height of the navigation header and tabBarOptions.keyboardHidesTabBar can be set to keep the tab bar from being shown when the keyboard is up. Due to a bug with calculating height on Android phones with notches, KeyboardAvoidingView is recommended over other solutions that involve calculating the height of the window.

adding an opaque background status bar on app.json (even though android:windowSoftInputMode="adjustResize" is set internally on Expo's Android apps, the translucent status bar causes it not to work): https://docs.expo.io/versions/latest/guides/configuration.html#androidstatusbar

If you plan to use GiftedChat inside a Modal, see #200.

Notes for local development

Native

  1. Install yarn global add expo-cli
  2. Install dependenciesyarn install
  3. expo start

react-native-web

With expo

  1. Install yarn global add expo-cli
  2. Install dependenciesyarn install
  3. expo start -w

Upgrade snack version

With create-react-app

  1. yarn add -D react-app-rewired
  2. touch config-overrides.js
module.exports = function override(config, env) {
  config.module.rules.push({
    test: /\.js$/,
    exclude: /node_modules[/\\](?!react-native-gifted-chat|react-native-lightbox|react-native-parsed-text)/,
    use: {
      loader: 'babel-loader',
      options: {
        babelrc: false,
        configFile: false,
        presets: [
          ['@babel/preset-env', { useBuiltIns: 'usage' }],
          '@babel/preset-react',
        ],
        plugins: ['@babel/plugin-proposal-class-properties'],
      },
    },
  })

  return config
}

You will find an example and a web demo here: xcarpentier/gifted-chat-web-demo

Another example with Gatsby : xcarpentier/clean-archi-boilerplate

Questions

License

Author

Feel free to ask me questions on Twitter @FaridSafi! or @xcapetir!

Contributors

The future of GiftedChat πŸŽ‰

Please give us your advice: Related PR

Please vote

GiftedChat depends on other packages and some needs a boost, please vote for PRs will improve it, thanks:

Hire an expert!

Looking for a ReactNative freelance expert with more than 14 years of experience? Contact Xavier from his website!

Demo Web πŸ–₯

Snack GiftedChat playground

Author: FaridSafi
Source Code: https://github.com/FaridSafi/react-native-gifted-chat 
License: MIT license

#react #javascript #chat 

React-native-gifted-chat: The Most Complete Chat UI for React Native

Google Map Library for React That Allows Rendering Components

Google Map React Β· 

google-map-react is a component written over a small set of the Google Maps API. It allows you to render any React component on the Google Map. It is fully isomorphic and can render on a server. Additionally, it can render map components in the browser even if the Google Maps API is not loaded. It uses an internal, tweakable hover algorithm - every object on the map can be hovered.

It allows you to create interfaces like this example (You can scroll the table, zoom/move the map, hover/click on markers, and click on table rows)

Getting started

In the simple case you just need to add lat and lng props to any child of GoogleMapReact component.

See it in action at jsbin

import React from "react";
import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({ text }) => <div>{text}</div>;

export default function SimpleMap(){
  const defaultProps = {
    center: {
      lat: 10.99835602,
      lng: 77.01502627
    },
    zoom: 11
  };

  return (
    // Important! Always set the container height explicitly
    <div style={{ height: '100vh', width: '100%' }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "" }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}
      >
        <AnyReactComponent
          lat={59.955413}
          lng={30.337844}
          text="My Marker"
        />
      </GoogleMapReact>
    </div>
  );
}

My map doesn't appear!

  • Make sure the container element has width and height. The map will try to fill the parent container, but if the container has no size, the map will collapse to 0 width / height. This is not a requirement for google-map-react, its a requirement for google-maps in general.

Installation

npm:

npm install --save google-map-react

yarn:

yarn add google-map-react

Features

Works with your Components

Instead of the default Google Maps markers, balloons and other map components, you can render your cool animated react components on the map.

Isomorphic Rendering

It renders on the server. (Welcome search engines) (you can disable javascript in browser dev tools, and reload any example page to see how it works)

Component Positions Calculated Independently of Google Maps API

It renders components on the map before (and even without) the Google Maps API loaded.

Google Maps API Loads on Demand

There is no need to place a <script src= tag at top of page. The Google Maps API loads upon the first usage of the GoogleMapReact component.

Use Google Maps API

You can access to Google Maps map and maps objects by using onGoogleApiLoaded, in this case you will need to set yesIWantToUseGoogleMapApiInternals to true

...

const handleApiLoaded = (map, maps) => {
  // use map and maps objects
};

...

<GoogleMapReact
  bootstrapURLKeys={{ key: /* YOUR KEY HERE */ }}
  defaultCenter={this.props.center}
  defaultZoom={this.props.zoom}
  yesIWantToUseGoogleMapApiInternals
  onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
>
  <AnyReactComponent
    lat={59.955413}
    lng={30.337844}
    text="My Marker"
  />
</GoogleMapReact>

PST: Remember to set yesIWantToUseGoogleMapApiInternals to true.

Example here

Internal Hover Algorithm

Now every object on the map can be hovered (however, you can still use css hover selectors if you want). If you try zooming out here example, you will still be able to hover on almost every map marker.

Examples

Placing react components on the map: simple (source)

Custom map options: example (source)

Hover effects: simple hover (source); distance hover (source)

GoogleMap events: example (source)

Example project: main (source); balderdash (same source as main)

Clustering example using Hooks (new: source, article) clustering-with-hooks

Clustering example (source) google-map-clustering-example

How to render thousands of markers (new: source) google-map-thousands-markers

Examples: Examples Old examples

jsbin example jsbin example

webpackbin examples (new) docs with webpackbin examples (In progress)

local develop example (new) develop example

Documentation

You can find the documentation here:

API Reference

NEW DOCS (In progress)

Contribute

Local development is broken into two parts (ideally using two tabs).

First, run rollup to watch your src/ module and automatically recompile it into dist/ whenever you make changes.

npm start # runs rollup with watch flag

The second part will be running the example/ create-react-app that's linked to the local version of your module.

# (in another tab)
cd example
npm start # runs create-react-app dev server

Now, anytime you make a change to your library in src/ or to the example app's example/src, create-react-app will live-reload your local dev server so you can iterate on your component in real-time.

Manual link-install

If you get the error Module not found: Can't resolve 'google-react-map'... while trying to run the example app, you need to manually link your local development module, try the following steps:

  1. In the root folder:
npm link
  1. Go into example/ and (after installing other dependencies) execute:
npm link google-map-react

Known Issues

!!! We are looking for contributors

We're actively looking for contributors, please send a message to the Owner or any of the Collaborators.

Author: Google-map-react
Source Code: https://github.com/google-map-react/google-map-react 
License: MIT license

#react #javascript #map #google 

Google Map Library for React That Allows Rendering Components
Dexter  Goodwin

Dexter Goodwin

1653263520

An Unified React Native Picker Modal Component for iOS and Android

React Native Picker Modal View

React Native Module to select item picker modal.

Created by Pankod

An alternative to Picker and PickerIOS components with an unified API and consistent look & feel on both plaforms. It's fully configurable and includes built-in support for text search and alphabetical index. Ideal for longer lists not suitable for "wheel-pickers".

Getting started

$ npm install react-native-picker-modal-view --save

or

$ yarn add react-native-picker-modal-view

Live Demo with Expo

Explore with Expo Snack

Example

import * as React from 'react';
import { Button, SafeAreaView, Text, View } from 'react-native';

import PickerModal from 'react-native-picker-modal-view';

import data from '../../../top20.json';

export default class Main extends React.Component<{}, { selectedItem: {} }> {

    constructor(props: {}) {
        super(props);

        this.state = {
            selectedItem: {}
        };
    }

    public render(): JSX.Element {
        const { selectedItem } = this.state;

        return (
            <SafeAreaView style={{ flex: 1, justifyContent: 'center', marginHorizontal: 20 }}>
                <PickerModal
                    renderSelectView={(disabled, selected, showModal) =>
                        <Button disabled={disabled} title={'Show me!'} onPress={showModal} />
                    }
                    onSelected={this.onSelected.bind(this)}
                    onClosed={this.onClosed.bind(this)}
                    onBackButtonPressed={this.onBackButtonPressed.bind(this)}
                    items={data}
                    sortingLanguage={'tr'}
                    showToTopButton={true}
                    selected={selectedItem}
                    showAlphabeticalIndex={true}
                    autoGenerateAlphabeticalIndex={true}
                    selectPlaceholderText={'Choose one...'}
                    onEndReached={() => console.log('list ended...')}
                    searchPlaceholderText={'Search...'}
                    requireSelection={false}
                    autoSort={false}
                />
                <View style={{ padding: 10, alignItems: 'center', backgroundColor: '#ddd' }}>
                    <Text>Chosen: </Text>
                    <Text>{JSON.stringify(selectedItem)}</Text>
                </View>
            </SafeAreaView>
        );
    }

    private onClosed(): void {
        console.log('close key pressed');
    }

    private onSelected(selected: any): void {
        this.setState({ selectedItem: selected });

        return selected;
    }

    private onBackButtonPressed(): void {
        console.log('back key pressed');
    }
}

Options

PropertiesTypeDescriptionDefault
modalAnimationTypestringThe RN Modal show/hide animation type"slide"
showAlphabeticalIndexbooleanHides alphabetical index"true"
onClosedFunctionFired when the modal is closed 
onBackButtonPressedFunctionFired when the back key is pressed 
onSelected 
*required
FunctionReturns selected item object"{Id, Name, Value, [key: string]: any}"
items 
*required
arrayArray of list items"[{Id, Name, Value, [key: string]: any}]"
renderSelectViewElementRender Select Component<SelectBoxComponent (built-in)>
renderListItemElementRender List item<ListItemComponent (built-in)/>
alphabeticalIndexCharsarrayChracters array for the alphabetical index<Turkish alphabet chracters>
searchInputTextColorstringSearch input placeholder text color"#252525"
keyExtractorFunctionFlatlist defined {key} function<Predefined return map index>
autoGenerateAlphabeticalIndexbooleanAuto-generates alphabetical index from list items data"false"
sortingLanguagestringCountry ISO (Alpha 2) Code for localeCompare"tr"
showToTopButtonbooleanButton for scroll to offset 0"true"
onEndReachedFunctionFired when the list reaches the end 
selectPlaceholderTextstringSelect box placeholder text"Choose one..."
searchPlaceholderTextstringSearch input placeholder text"Search..."
selectedobjectDefault selected item 
autoSortbooleanAuto-sort data list"false"
disabledbooleanDisable Select box 
requireSelectionbooleanRequire at least one list item is selected"false"
backButtonDisabledbooleanHide to back button"false"
renderSearchFunctionRender custom search input``

Core Props of React Native

PropertiesTypeDescriptionDefault
ModalPropsobjectReact Native Modal Props 
FlatListPropsobjectReact Native Flatlist Props 
SearchInputPropsobjectReact Native TextInput Props 

Running example project

You should have React Expo CLI to be installed in order to run example. Follow this instructions if you need to install Expo CLI.

Install the dependencies:

npm install

Once the installation is done, you can run the following command:

npm

npm start

You can also use:

expo

 expo start

yarn

 expo start

Notes

  • Auto-alphabetical index supported for Turkish and English languages.

Releases

  • 1.3.2 - Added renderSearch feature #54 Thanks to @murilo-campaner
  • 1.3.1 - Fixed #44 Thanks to @fnando
  • 1.3.0 - No back button support #42 Thanks to @ChildishForces
  • 1.2.8 - Fixed #37
  • 1.2.6 - Deprecated lifecycle methods fix
  • 1.2.5 - Flatlist initialNumToRender property hotfix
  • 1.2.3 - Refactor and code coverage
  • 1.2.2 - Fixed #5
  • 1.2.0 - Added renderSelectView and renderListItem properties.
  • 1.0.0 - Initial release

Author: Pankod
Source Code: https://github.com/pankod/react-native-picker-modal-view 
License: 

#react #javascript #typescript 

An Unified React Native Picker Modal Component for iOS and Android

React-map-gl: React friendly API wrapper around MapboxGL JS

react-map-gl

react-map-gl is a suite of React components designed to provide a React API for Mapbox GL JS-compatible libraries. More information in the online documentation.

See our Design Philosophy.

Installation

Using react-map-gl requires react >= 16.3.

npm install --save react-map-gl mapbox-gl

Example

import * as React from 'react';
import Map from 'react-map-gl';

function App() {
  return <Map
    initialViewState={{
      longitude: -100,
      latitude: 40,
      zoom: 3.5
    }}
    style={{width: 600, height: 400}}
    mapStyle="mapbox://styles/mapbox/streets-v9"
  />;
}

Using Mapbox Tokens

Starting with v2.0, mapbox-gl requires a Mapbox token for any usage, with or without the Mapbox data service. See about Mapbox tokens for your options.

To show maps from a service such as Mapbox you will need to register on their website in order to retrieve an access token required by the map component, which will be used to identify you and start serving up map tiles. The service will be free until a certain level of traffic is exceeded.

There are several ways to provide a token to your app, as showcased in some of the example folders:

  • Provide a mapboxAccessToken prop to the map component
  • Set the MapboxAccessToken environment variable (or set REACT_APP_MAPBOX_ACCESS_TOKEN if you are using Create React App)
  • Provide it in the URL, e.g ?access_token=TOKEN

Docs

Contribute

See contribution guide.

Attributions

react-map-gl is part of vis.gl, an Urban Computing Foundation project.

Author: Visgl
Source Code: https://github.com/visgl/react-map-gl 
License: View license

#react #javascript #typescript #maps 

React-map-gl: React friendly API wrapper around MapboxGL JS
Dexter  Goodwin

Dexter Goodwin

1653256020

Google Sign-in for Your React Native Applications

Features

  • Support all 3 types of authentication methods (standard, with server-side validation or with offline access (aka server side access))
  • Promise-based API consistent between Android and iOS
  • Typings for TypeScript and Flow
  • Native sign in buttons

Requirements

  • RN >= 0.60

Project setup and initialization

yarn add @react-native-google-signin/google-signin

Then follow the Android guide and iOS guide

Expo installation

This package cannot be used in the "Expo Go" app because it requires custom native code. However, you can add custom native code to expo by following the guide below.

expo install @react-native-google-signin/google-signin

After installing this npm package, add the config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "android": {
      "googleServicesFile": "./google-services.json"
    },
    "ios": {
      "googleServicesFile": "./GoogleService-Info.plist"
    },
    "plugins": ["@react-native-google-signin/google-signin"]
  }
}

Next, rebuild your app as described in the "Adding custom native code" guide.

Public API

1. GoogleSignin

import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from '@react-native-google-signin/google-signin';

configure(options)

It is mandatory to call this method before attempting to call signIn() and signInSilently(). This method is sync meaning you can call signIn / signInSilently right after it. In typical scenarios, configure needs to be called only once, after your app starts. In the native layer, this is a synchronous call. All parameters are optional.

Example usage with default options: you get user email and basic profile info.

import { GoogleSignin } from '@react-native-google-signin/google-signin';

GoogleSignin.configure();

An example with all options enumerated:

GoogleSignin.configure({
  scopes: ['https://www.googleapis.com/auth/drive.readonly'], // [Android] what API you want to access on behalf of the user, default is email and profile
  webClientId: '<FROM DEVELOPER CONSOLE>', // client ID of type WEB for your server (needed to verify user ID and offline access)
  offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
  hostedDomain: '', // specifies a hosted domain restriction
  forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *.
  accountName: '', // [Android] specifies an account name on the device that should be used
  iosClientId: '<FROM DEVELOPER CONSOLE>', // [iOS] if you want to specify the client ID of type iOS (otherwise, it is taken from GoogleService-Info.plist)
  googleServicePlistPath: '', // [iOS] if you renamed your GoogleService-Info file, new name here, e.g. GoogleService-Info-Staging
  openIdRealm: '', // [iOS] The OpenID2 realm of the home web server. This allows Google to include the user's OpenID Identifier in the OpenID Connect ID token.
  profileImageSize: 120, // [iOS] The desired height (and width) of the profile image. Defaults to 120px
});

* forceCodeForRefreshToken docs

signIn(options: { loginHint?: string })

Prompts a modal to let the user sign in into your application. Resolved promise returns an userInfo object. Rejects with error otherwise.

Options: an object which contains a single key:

loginHint: [iOS-only] The user's ID, or email address, to be prefilled in the authentication UI if possible. See docs here

// import statusCodes along with GoogleSignin
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';

// Somewhere in your code
signIn = async () => {
  try {
    await GoogleSignin.hasPlayServices();
    const userInfo = await GoogleSignin.signIn();
    this.setState({ userInfo });
  } catch (error) {
    if (error.code === statusCodes.SIGN_IN_CANCELLED) {
      // user cancelled the login flow
    } else if (error.code === statusCodes.IN_PROGRESS) {
      // operation (e.g. sign in) is in progress already
    } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
      // play services not available or outdated
    } else {
      // some other error happened
    }
  }
};

addScopes(options: { scopes: Array<string> })

This is an iOS-only method (calls getCurrentUser() on Android) that resolves with null or userInfo object. When calling signIn on iOS, only basic profile scopes (email, profile, openid) are requested. If you want access to more scopes, use this call. Read more about this here.

Example:

const user = await GoogleSignin.addScopes({
  scopes: ['https://www.googleapis.com/auth/user.gender.read'],
});

signInSilently()

May be called eg. in the componentDidMount of your main component. This method returns the current user and rejects with an error otherwise.

To see how to handle errors read signIn() method

getCurrentUserInfo = async () => {
  try {
    const userInfo = await GoogleSignin.signInSilently();
    this.setState({ userInfo });
  } catch (error) {
    if (error.code === statusCodes.SIGN_IN_REQUIRED) {
      // user has not signed in yet
    } else {
      // some other error
    }
  }
};

isSignedIn()

This method may be used to find out whether some user is currently signed in. It returns a promise which resolves with a boolean value (it never rejects). In the native layer, this is a synchronous call. This means that it will resolve even when the device is offline. Note that it may happen that isSignedIn() resolves to true and calling signInSilently() rejects with an error (eg. due to a network issue).

isSignedIn = async () => {
  const isSignedIn = await GoogleSignin.isSignedIn();
  this.setState({ isLoginScreenPresented: !isSignedIn });
};

getCurrentUser()

This method resolves with null or userInfo object. The call never rejects and in the native layer, this is a synchronous call. Note that on Android, accessToken is always null in the response.

getCurrentUser = async () => {
  const currentUser = await GoogleSignin.getCurrentUser();
  this.setState({ currentUser });
};

clearCachedAccessToken(accessTokenString)

This method only has an effect on Android. You may run into a 401 Unauthorized error when a token is invalid. Call this method to remove the token from local cache and then call getTokens() to get fresh tokens. Calling this method on iOS does nothing and always resolves. This is because on iOS, getTokens() always returns valid tokens, refreshing them first if they have expired or are about to expire (see docs).

getTokens()

Resolves with an object containing { idToken: string, accessToken: string, } or rejects with an error. Note that using accessToken for identity assertion on your backend server is discouraged.

signOut()

Signs out the current user.

signOut = async () => {
  try {
    await GoogleSignin.signOut();
    this.setState({ user: null }); // Remember to remove the user from your app's state as well
  } catch (error) {
    console.error(error);
  }
};

revokeAccess()

Removes your application from the user authorized applications. Read more about it here and here.

revokeAccess = async () => {
  try {
    await GoogleSignin.revokeAccess();
    // Google Account disconnected from your app.
    // Perform clean-up actions, such as deleting data associated with the disconnected account.
  } catch (error) {
    console.error(error);
  }
};

hasPlayServices(options)

Checks if device has Google Play Services installed. Always resolves to true on iOS.

Presence of up-to-date Google Play Services is required to show the sign in modal, but it is not required to perform calls to configure and signInSilently. Therefore, we recommend to call hasPlayServices directly before signIn.

try {
  await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
  // google services are available
} catch (err) {
  console.error('play services are not available');
}

hasPlayServices accepts one parameter, an object which contains a single key: showPlayServicesUpdateDialog (defaults to true). When showPlayServicesUpdateDialog is set to true the library will prompt the user to take action to solve the issue, as seen in the figure below.

You may also use this call at any time to find out if Google Play Services are available and react to the result as necessary.

prompt install

statusCodes

These are useful when determining which kind of error has occured during sign in process. Import statusCodes along with GoogleSignIn. Under the hood these constants are derived from native GoogleSignIn error codes and are platform specific. Always prefer to compare error.code to statusCodes.SIGN_IN_CANCELLED or statusCodes.IN_PROGRESS and not relying on raw value of the error.code.

NameDescription
SIGN_IN_CANCELLEDWhen user cancels the sign in flow
IN_PROGRESSTrying to invoke another operation (eg. signInSilently) when previous one has not yet finished. If you call eg. signInSilently twice, 2 calls to signInSilently in the native module will be done. The promise from the first call to signInSilently will be rejected with this error, and the second will resolve / reject with the result of the native module.
SIGN_IN_REQUIREDUseful for use with signInSilently() - no user has signed in yet
PLAY_SERVICES_NOT_AVAILABLEPlay services are not available or outdated, this can only happen on Android

Example how to use statusCodes.

2. GoogleSigninButton

signin button

import { GoogleSignin, GoogleSigninButton } from '@react-native-google-signin/google-signin';

<GoogleSigninButton
  style={{ width: 192, height: 48 }}
  size={GoogleSigninButton.Size.Wide}
  color={GoogleSigninButton.Color.Dark}
  onPress={this._signIn}
  disabled={this.state.isSigninInProgress}
/>;

Props

size

Possible values:

  • Size.Icon: display only Google icon. Recommended size of 48 x 48.
  • Size.Standard: icon with 'Sign in'. Recommended size of 230 x 48.
  • Size.Wide: icon with 'Sign in with Google'. Recommended size of 312 x 48.

Default: Size.Standard. Given the size prop you pass, we'll automatically apply the recommended size, but you can override it by passing the style prop as in style={{ width, height }}.

color

Possible values:

  • Color.Dark: apply a blue background
  • Color.Light: apply a light gray background

disabled

Boolean. If true, all interactions for the button are disabled.

onPress

Handler to be called when the user taps the button

Inherited View props...

3. userInfo

Example userInfo which is returned after successful sign in.

{
  idToken: string,
  serverAuthCode: string,
  scopes: Array<string>, // on iOS this is empty array if no additional scopes are defined
  user: {
    email: string,
    id: string,
    givenName: string,
    familyName: string,
    photo: string, // url
    name: string // full name
  }
}

Want to contribute?

Check out the contributor guide!

Notes

Calling the methods exposed by this package may involve remote network calls and you should thus take into account that such calls may take a long time to complete (eg. in case of poor network connection).

idToken Note: idToken is not null only if you specify a valid webClientId. webClientId corresponds to your server clientID on the developers console. It HAS TO BE of type WEB

Read iOS documentation and Android documentation for more information

serverAuthCode Note: serverAuthCode is not null only if you specify a valid webClientId and set offlineAccess to true. once you get the auth code, you can send it to your backend server and exchange the code for an access token. Only with this freshly acquired token can you access user data.

Read iOS documentation and Android documentation for more information.

Additional scopes

The default requested scopes are email and profile.

If you want to manage other data from your application (for example access user agenda or upload a file to drive) you need to request additional permissions. This can be accomplished by adding the necessary scopes when configuring the GoogleSignin instance.

Please visit https://developers.google.com/identity/protocols/googlescopes or https://developers.google.com/oauthplayground/ for a list of available scopes.

Troubleshooting

Please see the troubleshooting section in the Android guide and iOS guide.

🚧🚧 Maintenance notice 🚧🚧

See this issue

Author: React-native-google-signin
Source Code: https://github.com/react-native-google-signin/google-signin 
License: MIT license

#react #javascript #oauth2 #reactnative 

Google Sign-in for Your React Native Applications
Queenie  Davis

Queenie Davis

1653253200

React Design Editor: A Module for React, Written in JS / Typescript

React Design Editor  

React Design Editor is a module for React, written in Javascript/Typescript which provides two primary features:

  • Image Editor - Create images in React, draw diagrams and arrange compositions using the image editor and save the result to one of several export formats, provides functionality similar to Powerpoint.
  • Business Process Modelling (BPM) - Design flowcharts and process workflows in React and export the model to JSON, which can be imported into the tool (load/save).

The module primarily uses the Ant Design, Fabric.js and React libraries, but a full list of required dependencies can be found below.

Try it out today - the project is being continually developed to support a variety of different functions.

View Demo

Feature List

  •  Add, remove, resize, reorder, clone, copy/paste and drag/drop elements
  •  Drawing capability, with polygon, line, arrows and link support
  •  Preview mode, tooltips, group/ungroup and zoom functionality
  •  Upload (with drag/drop), import and export to JSON or image
  •  Image cropping, Image filters, alignment, alignment guides
  •  Snap to grid, context menu, animation and video element
  •  Various icons in icon picker and fonts from Google Fonts (20)
  •  HTML/CSS/JS Element, iFrame element
  •  Animation support, with Fade / Bounce / Shake / Scaling / Rotation / Flash effects
  •  Code Editor with HTML / CSS / JS / Preview
  •  Various interaction modes, including grasp, selection, ctrl + drag grab
  •  Multiple layouts, with fixed, responsive, fullscreen and grid modes
  •  SVG, Chart and GIF elements
  •  Undo/Redo support
  •  Wireframes - in development
  •  Multiple Map - in development
  •  Ruler - in development

Installation

Run npm install react-design-editor or yarn add react-design-editor

Getting Started

  1. Clone this Project with git clone https://github.com/salgum1114/react-design-editor.git
  2. Install dependencies with npm install or yarn
  3. Run the App with npm start or yarn start
  4. Open your web browser to http://localhost:4000

Screenshots

Image Map Editor

1. Fixed Layout Mode

fixed

2. Responsive Layout Mode

responsive

3. Full Screen Layout Mode

fullscreen

4. Preview Mode

preview

Workflow Editor

workflow


Author: salgum1114
Source Code: https://github.com/salgum1114/react-design-editor
License: MIT license

#react-native #react #typescript #javascript 

React Design Editor: A Module for React, Written in JS / Typescript

React-gmaps: A Google Maps Component for React.js

React Gmaps

A Google Maps component for React.js

Features

  • Lazy Google Maps loading
  • Easy to use

Installation

$ npm install react-gmaps --save

Demo

http://react-gmaps.herokuapp.com/

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import {Gmaps, Marker, InfoWindow, Circle} from 'react-gmaps';

const coords = {
  lat: 51.5258541,
  lng: -0.08040660000006028
};

const params = {v: '3.exp', key: 'YOUR_API_KEY'};

class App extends React.Component {

  onMapCreated(map) {
    map.setOptions({
      disableDefaultUI: true
    });
  }

  onDragEnd(e) {
    console.log('onDragEnd', e);
  }

  onCloseClick() {
    console.log('onCloseClick');
  }

  onClick(e) {
    console.log('onClick', e);
  }

  render() {
    return (
      <Gmaps
        width={'800px'}
        height={'600px'}
        lat={coords.lat}
        lng={coords.lng}
        zoom={12}
        loadingMessage={'Be happy'}
        params={params}
        onMapCreated={this.onMapCreated}>
        <Marker
          lat={coords.lat}
          lng={coords.lng}
          draggable={true}
          onDragEnd={this.onDragEnd} />
        <InfoWindow
          lat={coords.lat}
          lng={coords.lng}
          content={'Hello, React :)'}
          onCloseClick={this.onCloseClick} />
        <Circle
          lat={coords.lat}
          lng={coords.lng}
          radius={500}
          onClick={this.onClick} />
      </Gmaps>
    );
  }

};

ReactDOM.render(<App />, document.getElementById('gmaps'));

Test

$ npm test

Author: MicheleBertoli
Source Code: https://github.com/MicheleBertoli/react-gmaps 
License: MIT license

#react #javascript #maps 

React-gmaps: A Google Maps Component for React.js
Dexter  Goodwin

Dexter Goodwin

1653248460

iOS/android Native Vector Assets Generated From SVG

React Native Vector Image

iOS/Android native vector assets generated from SVG. 

  • Faster render – ~5x faster than react-native-svg.
  • Smaller JS bundle = faster startup.
  • Native support for dark mode.

Installation

yarn add react-native-vector-image @klarna/react-native-vector-drawable

Android

Edit android/app/build.gradle to look like this (without the +):

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"
+ apply from: "../../node_modules/react-native-vector-image/strip_svgs.gradle"

iOS

Open your project in Xcode, select the Build Phases tab, and edit the Bundle React Native code and images script to look like this (without the +):

set -e

export NODE_BINARY=node
../node_modules/react-native/scripts/react-native-xcode.sh
+ ../node_modules/react-native-vector-image/strip_svgs.sh

Usage

Since native vector assets cannot be served over http via metro dev server, they must be generated and compiled into the app bundle.

Step 1: import an .svg file

import VectorImage from 'react-native-vector-image';

const App = () => <VectorImage source={require('./image.svg')} />;

To add dark mode to your image, create a new file with an .dark.svg extension, ie image.svg = light and image.dark.svg = dark.

Step 2: generate native assets

This takes a while as metro has to go through all the code to find the imported SVGs.

yarn react-native-vector-image generate
ArgumentDescriptionDefault
--entry-filePath to the app entrypoint file.index.js
--configPath to the metro config file.metro.config.js
--reset-cacheReset metro cache before extracting SVG assets.false
--ios-outputPath to an iOS .xcassets folder.ios/AppName/Images.xcassets
--no-ios-outputDisable iOS output.false
--android-outputPath to an Android res folder.android/app/src/main/res
--no-android-outputDisable Android output.false

Step 3: recompile

yarn react-native run-ios
# or
yarn react-native run-android

Troubleshooting

generate command outputs "Error while parsing image.svg"

Some optimizations applied by SVGO are not compatible with the SVG parser on Android. Try to re-export the SVG without optimizing it.

<VectorImage /> warns "Could not find image"

It means that the native vector asset does not exist or is out of sync with the SVG. Simply generate the files and recompile the app.

Author: Oblador
Source Code: https://github.com/oblador/react-native-vector-image 
License: MIT license

#react #javascript #svg #reactnative 

iOS/android Native Vector Assets Generated From SVG

React-google-maps: React.js Google Maps integration Component

react-google-maps

React.js Google Maps integration component

Getting Help

Before doing this, did you:

  1. Read the documentation
  2. Read the source code

You can get someone's help in three ways:

  1. Ask on StackOverflow with a google-maps tag or use react-google-maps as a keyword
  2. Ask in the chat room
  3. Create a Pull Request with your solutions to your problem

Please, be noted, no one, I mean, no one, is obligated to help you in ANY means. Your time is valuable, so does our contributors. Don't waste our time posting questions like β€œhow do I do X with React-Google-Maps” and β€œmy code doesn't work”. This is not the primary purpose of the issue tracker. Don't abuse.

For contributors

Some simple guidelines

  • Don't manually modify lib folder. They're generated during yarn release process
  • Follow conventional-commits-specification
  • standard-version
  • Auto generated: src/macros -> src/components -> lib/components
  • Other components are manually maintained
  • Use yarn and keep yarn.lock updated in PR
  • Discuss! Discuss! Discuss!

Introduction

Installation

Usage & Configuration

Changelog

The changelog is automatically generated via standard-version and can be found in project root as well as npm tarball.

Demo App

Author: Tomchentw
Source Code: https://github.com/tomchentw/react-google-maps 
License: MIT license

#react #javascript #maps 

React-google-maps: React.js Google Maps integration Component