Dynamic icons import with material ui icons - material-ui

is there a way to import svg icons dynamicly based on a json file using Material-ui Svg icons?
Here's an example of my json file:
[
{
"name": "home",
"icon": "Home",
"title": "Home"
},
{
"name": "business",
"icon": "Business",
"title": "Business"
},
{
"name": "apartment",
"icon": "Apartment",
"title": "Apartment"
}
]
I want to map this json to create a menu list with icons

For those who need the same I've created a custom Icon component with a list of icons
import ApartmentIcon from '/path/to/icon';
import BusinessIcon from '/path/to/icon';
import HomeIcon from '/path/to/icon';
const IconList = {
apartment: ApartmentIcon,
business: BusinessIcon,
home: HomeIcon,
}
const Icon = ({ icon, ...props }) => {
const Component = Icons[icon];
return <Component {...props} />;
};
export default Icon;
So I can import the Icon component and then map the json to get the icon
menuJson.map((menuItem) => <Icon icon={menuItem.name} />)
Feel free to reach out if you need help with another implementation

// sample to your json:
const dynamicIcon: { [key: number]: React.ReactElement<SvgIconProps> } = {
home: <Home />,
business: <Business />,
apartment: <Apartment />,
};
// code usage:
<Box>
{ dynamicIcon['home'] }
</Box>

Related

Write custom transform file for design tokens from Figma in Style Dictionary for Flutter

I have barebone Flutter 2.5 project and Figma design tokens which were exported via Figma Tokens.
Those design tokens look like this:
project\style_dictionary\properties\tokens.json
{
"borderWidth": {
"100": {
"value": "1.5",
"type": "borderWidth"
}
},
"opacity": {
"basic": {
"100": {
"value": "0.04",
"type": "opacity"
}
}
},
"colors": {
"basic": {
"red": {
"50": {
"value": "#ffebee",
"type": "color"
}
}
}
}
}
and Style Dictionary config which looks like this
project\style_dictionary\config.json
{
"source": [
"properties/*.json"
],
"platforms": {
"flutter": {
"transformGroup": "flutter",
"buildPath": "../lib/unique_file/",
"files": [
{
"destination": "style_dictionary.dart",
"format": "flutter/class.dart",
"className": "StyleDictionary"
}
]
},
"flutter-separate": {
"transformGroup": "flutter-separate",
"buildPath": "../lib/unique_file/",
"files": [
{
"destination": "style_dictionary_color.dart",
"format": "flutter/class.dart",
"className": "StyleDictionaryColor",
"type": "color",
"filter": {
"attributes": {
"category": "colors"
}
}
}
]
}
}
}
Running style-dictionary build in CMD in style_dictionary will generate next file
project\lib\unique_file\style_dictionary_color.dart
import 'dart:ui';
class StyleDictionaryColor {
StyleDictionaryColor._();
static const basicRed50 = #ffebee;
}
But in should be like that at the end
project\lib\unique_file\style_dictionary_color.dart
import 'dart:ui';
class StyleDictionaryColor {
StyleDictionaryColor._();
static const basicRed50 = Color(0xFFFFEBEE);
}
Question:
How and where can I create Style Dictionary transforms file to create right dart file with Color type of the static variable?
I cannot modify exported design tokens.
Create a project\build.js as a custom Transforms file. Logic of creation was used from default Flutter color transforms and Documentation
const StyleDictionary = require('style-dictionary')
const baseConfig = require('./style_dictionary/config.json')
const Color = require('tinycolor2')
StyleDictionary.registerTransform({
name: 'colors/hex8flutter',
type: 'value',
matcher: prop => {
return prop.attributes.category === 'colors'
},
transformer: prop => {
var str = Color(prop.value).toHex8().toUpperCase();
return `Color(0x${str.slice(6)}${str.slice(0, 6)})`;
},
})
const StyleDictionaryExtended = StyleDictionary.extend(baseConfig)
StyleDictionaryExtended.buildAllPlatforms()
Modify project\style_dictionary\config.json so it can be executed from project directory and include new transforms - "transformColorsToColor" together with other transforms from Flutter
{
"source": [
"style_dictionary/properties/*.json"
],
"platforms": {
"flutter": {
"transforms": ["attribute/cti", "name/cti/camel", "color/hex8flutter", "size/flutter/remToDouble", "content/flutter/literal", "asset/flutter/literal", "font/flutter/literal", "colors/hex8flutter"],
"buildPath": "lib/unique_file/",
"files": [
{
"destination": "style_dictionary.dart",
"format": "flutter/class.dart",
"className": "StyleDictionary"
}
]
},
"flutter-separate": {
"transforms": ["attribute/cti", "name/ti/camel", "color/hex8flutter", "size/flutter/remToDouble", "content/flutter/literal", "asset/flutter/literal", "font/flutter/literal", "colors/hex8flutter"],
"buildPath": "lib/unique_file/",
"files": [
{
"destination": "style_dictionary_color.dart",
"format": "flutter/class.dart",
"className": "StyleDictionaryColor",
"type": "color",
"filter": {
"attributes": {
"category": "colors"
}
}
}
]
}
}
}
Run npm init with all default answers
Run npm install --save tinycolor2
Run node build.js

How can I use my GeoJSON data in my next.js app with leaflet?

In my Next.js app I try to use multiple locations on my leaflet map by using a GeoJSON data file.
When I use one location in the map it works just fine, but when I import the data and map over it to show more points on the map, I run in two the Unhandled Runtime Errors:
TypeError: Cannot read property 'lat' of null
and
TypeError: Cannot read property 'lat' of undefined
When I console log the imported data I can see the correct data.
Does anybody know what I am doing wrong?
This are the files I use:
components/Map/index.js
import dynamic from 'next/dynamic'
const Map = dynamic(
() => import('./Map'),
{ ssr: false }
)
export default Map;
components/Map/Map.js
import 'leaflet/dist/leaflet.css'
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import * as data from './seedlibraryData.json';
function Map() {
// console.log('data geometry coordinate 1', data.features[0].geometry.coordinates[0])
// console.log('data geometry coordinate 2', data.features[0].geometry.coordinates[1])
return(
<div>
<MapContainer
center={[52.080190, 4.310130]}
zoom={13}
scrollWheelZoom={true}
className="leaflet-container"
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© OpenStreetMap contributors'
/>
{data.features.map(seedlibrary => (
<Marker
key={seedlibrary.properties.library_ID}
position={
seedlibrary.geometry.coordinates[1],
seedlibrary.geometry.coordinates[0]
}
animate={false}
/>
))}
<Popup>
Text
</Popup>
</MapContainer>
</div>
)
}
export default Map
components/Map/seedlibraryData.json:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"library_ID": "01",
"location_name": "Stadsoase Spinozahof",
"street": "Repelaerstraat 61",
"zipcode": "2515 LX",
"city": "Den Haag",
"website": "http://stadsoasespinozahof.nl/"
},
"geometry": {
"type": "Point",
"coordinates": [52.072421, 4.315050]
}
},
{
"type": "Feature",
"properties": {
"library_ID": "02",
"location_name": "Hof van Wouw",
"street": "Lange Beestenmarkt 49-85",
"zipcode": "2512 EB",
"city": "Den Haag",
"website": "https://hofvanwouw.nl/"
},
"geometry": {
"type": "Point",
"coordinates": [52.073980, 4.307760]
}
}
]
}
pages/index.js:
import React from 'react';
import Map from '../components/Map/'
function HomePage() {
return (
<div>
<div>
<Map />
</div>
</div>
)
}
export default HomePage
EDIT:
I found the solution: #ghybs pointed me in the good direction. I checked again the leaflet-react documentation. The popup tag should be inside the Marker tag. Instead I placed a self closing Marker tag in it.
Map.js solution:
import 'leaflet/dist/leaflet.css'
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import * as data from './seedlibraryData.json';
function Map() {
return(
<div>
<MapContainer
center={[52.080190, 4.310130]}
zoom={13}
scrollWheelZoom={true}
className="leaflet-container"
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© OpenStreetMap contributors'
/>
{data.features.map(seedlibrary => (
<Marker
key={seedlibrary.properties.library_ID}
position={[
seedlibrary.geometry.coordinates[0],
seedlibrary.geometry.coordinates[1]
]}
animate={false}
>
<Popup>
{seedlibrary.properties.location_name}
{seedlibrary.properties.street}
{seedlibrary.properties.zipcode}{seedlibrary.properties.city}
</Popup>
</Marker>
))}
</MapContainer>
</div>
)
}
export default Map
Your syntax to specify Marker position is suspicious:
<Marker
position={
seedlibrary.geometry.coordinates[1],
seedlibrary.geometry.coordinates[0]
}
/>
Seems like you should write the coordinates as an array, e.g.:
<Marker
position={[
seedlibrary.geometry.coordinates[1],
seedlibrary.geometry.coordinates[0]
]}
/>

Flutter Web: Implemented solution using HtmlElementView, IFrameElement, registerViewFactory is not working in ios

I have implemented a solution to integrate an online payment gateway in my flutter web project till now i have not found any other solution except this one. The link for the solution I have implemented in my flutter web project is This for refrence, now the problem is, this works fine in android web but it is not working in iOS web i don't know why.
can anyone help me with what is the problem with this or why it is not working in iOS?, or any other solution for implementing payment gateway in flutter web.
below is the code I have implemented from that article.
UiFake.dart
import 'dart:ui' as ui;
// ignore: camel_case_types
class platformViewRegistry {
static registerViewFactory(String viewId, dynamic cb) {
ui.platformViewRegistry.registerViewFactory(viewId, cb);
}
}
web/payment.html
<!DOCTYPE html><html>
<meta name="viewport" content="width=device-width">
<head><title>RazorPay Web Payment</title></head>
<body>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = {
"key": "YOUR_KEY_HERE",
"amount": "50000", "currency": "INR",
"name": "Acme Corp",
"description": "Test Transaction",
"image": "https://example.com/your_logo",
"handler": function (response){
window.parent.postMessage("SUCCESS","*"); //2
alert(response.razorpay_payment_id);
alert(response.razorpay_order_id);
alert(response.razorpay_signature)
},
"prefill": {
"name": "Gaurav Kumar",
"email": "gaurav.kumar#example.com",
"contact": "9999999999"
},
"notes": {
"address": "Autofy"
},
"theme": {
"color": "#DF0145"
},
"modal": {
"ondismiss": function(){
window.parent.postMessage("MODAL_CLOSED","*"); //3
}
}
};
var rzp1 = new Razorpay(options);
window.onload = function(e){ //1
rzp1.open();
e.preventDefault();
}
</script>
</body>
</html>
RazorPayWeb.dart
import 'dart:html';
import 'dart:ui' as ui;
//conditional import
import 'package:autofystore/utils/UiFake.dart' if (dart.library.html) 'dart:ui' as ui;
import 'package:flutter/material.dart';
class RazorPayWeb extends StatelessWidget {
#override
Widget build(BuildContext context) {
//register view factory
ui.platformViewRegistry.registerViewFactory("rzp-html",(int viewId) {
IFrameElement element=IFrameElement();
//Event Listener
window.onMessage.forEach((element) {
print('Event Received in callback: ${element.data}');
if(element.data=='MODAL_CLOSED'){
Navigator.pop(context);
}else if(element.data=='SUCCESS'){
print('PAYMENT SUCCESSFULL!!!!!!!');
}
});
element.requestFullscreen();
element.src='assets/html/payment.html';
element.style.border = 'none';
return element;
});
return Scaffold(
body: Builder(builder: (BuildContext context) {
return Container(
child: HtmlElementView(viewType: 'rzp-html'),
);
}));
}
}
Thanx in advance.
Comment out requestFullscreen():
//element.requestFullscreen();

How can I display facebook user name in react native?

I can log in into my app with facebook api. I would like to show a welcome message like this: Hi,(facebook name).
How can I do it?
I tried tho showing with: Hi,{displayName} but it didn't works.
//THIS IS THE LOGINSCREEN
async loginWithFacebook() {
const { type, token } = await
Expo.Facebook.logInWithReadPermissionsAsync('717955408626729',
{ permissions: ['email']['public_profile'] })
if (type == 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token)
firebase.auth().signInWithCredential(credential).catch((error) =>
{
})
}
}
render() {
return (
<View>
<Image
source={require('../assets/logo2.png')}
style={{ height: 280, width: 350, marginTop: -210 }}
/>
<View>
<Text>Benvenuto!</Text>
</View>
<TouchableOpacity
onPress={() => this.loginWithFacebook()}>
<Text>Accedi con Facebook</Text>
</TouchableOpacity>
</View>
);
}
}
You can use this, if you can get a Facebook name.
const data = { "displayName": "Mattia Cannavò", "email": null,
"emailVerified": false, "isAnonymous": false, "lastLoginAt": "1566314114729",
"phoneNumber": null, "photoURL": "graph.facebook.com/2177408949049079/picture",
"providerData": Array [ { "displayName": "Mattia Cannavò",
"email": "mattiacannavo08#gmail.com", "phoneNumber": null,
"photoURL": "graph.facebook.com/2177408949049079/picture",
"providerId": "facebook.com", "uid": "2177408949049079", } ] };
<Text>{`Hi ${data.displayName} `}</Text>

How import fabric-webpack to react-native?

I have existing iOS swift application. I integrate it to react-native. But when i added "import {Canvas,Circle, Image, Path} from 'react-fabricjs';" i have error
enter image description here
my package.json
{
"name": "uploader",
"version": "1.0.0",
"private": true,
"description": "Uploader",
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "~15.3.0",
"react-dom": "~15.3.0",
"react-fabricjs": "^0.1.6",
"react-native": "~0.34.0",
"jsdom": "~9.9.1"
}
}
my index.ios.js
'use strict';
// 1
import React from 'react';
import {Canvas,Circle, Image, Path } from 'react-fabricjs';
import ReactNative, {
AppRegistry,
StyleSheet,
Text,
View,
} from 'react-native';
// 2
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'yellow',
},
welcome: {
fontSize: 35,
color: 'green',
},
});
// 3
class AddRatingApp extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>See you later alligator !</Text>
</View>
)
}
}
// 4
AppRegistry.registerComponent('AddRatingApp', () => AddRatingApp);
How I can import any React library into react-native application?
Any libraries that uses html/css/DOM will not work with React Native. This one is a html5 library that will work with React, but not React Native.