How to use DatePicker inside tcomb-forn-native template? - react-native

I am working with
React Native
Expo
react-native-datepicker
tcomb-form-native
forms using templates
I did a register form that have the following struct
name: t.String,
email: formValidation.email,
password: formValidation.password,
gender: t.Boolean,
birthday: t.Date,
cellphone: t.Number
import React from "react";
import t from "tcomb-form-native";
import formValidation from "../utils/Validation";
import inputTemplate from "../forms/templates/Input";
import buttonGroupTemplate from "../forms/templates/ButtonGroup";
import datePickerTemplate from "../forms/templates/DatePicker";
import phoneInputTemplate from "../forms/templates/PhoneInput";
export const RegisterStruct = t.struct({
name: t.String,
email: formValidation.email,
password: formValidation.password,
gender: t.Boolean,
birthday: t.Date,
cellphone: t.Number
});
export const RegisterOptions = {
fields: {
name: {
template: inputTemplate,
config: {
placeholder: "Introduce tu nombre completo",
iconType: "material-community",
iconName: "account-outline"
}
},
email: {
template: inputTemplate,
config: {
placeholder: "Introduce tu correo electrónico",
iconType: "material-community",
iconName: "at"
}
},
password: {
template: inputTemplate,
config: {
placeholder: "Introduce tu clave",
iconType: "material-community",
iconName: "lock-outline",
password: true,
secureTextEntry: true
}
},
gender: {
template: buttonGroupTemplate,
config: {
buttons: ["Masculino", "Femenino"]
}
},
birthday: {
template: datePickerTemplate,
config: {
placeholder: "Selecciona tu fecha de nacimiento",
date: "2016-05-15"
}
},
cellphone: {
template: phoneInputTemplate,
config: {
placeholder: "Introduce tu número de celular"
}
}
}
};
And this is my template
import React from "react";
import { StyleSheet, View } from "react-native";
import DatePicker from "react-native-datepicker";
import { Dimensions } from "react-native";
import { red } from "ansi-colors";
export default (datePickerTemplate = locals => {
return (
<View style={styles.viewContainer}>
<DatePicker
style={styles.customDatePicker}
date={date}
mode="date"
placeholder={locals.config.placeholder}
format="DD-MM-YYYY"
minDate="01-05-2016"
maxDate="01-06-2020"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: "absolute",
right: 0,
top: 4,
marginRight: 0
},
dateInput: {
borderColor: "#FFFFFF",
borderBottomColor: "#3F3F3F"
},
placeholderText: {
alignSelf: "flex-start",
fontSize: 17
}
}}
onDateChange={date => locals.onChange(date)}
/>
</View>
);
});
const styles = StyleSheet.create({
viewContainer: {
flexDirection: "row",
marginTop: 12,
marginBottom: 12
},
customDatePicker: {
flex: 1,
marginRight: 10,
marginLeft: 10
}
});
When I choose a date on the calendar in the state it changes correctly but on the screen I see the same date, the date field in the user interface does not change should show the selected date.
I use the code below to show the date change on the console.
onChangeFormRegister = formValue => {
console.log(formValue);
this.setState({
formData: formValue
});
};
updateIndex(selectedIndex) {
this.setState({ selectedIndex });
}
render() {
const { registerStruct, registerOptions, formErrorMessage } = this.state;
return (
<ScrollView style={styles.viewBody}>
<Form
ref="registerForm"
type={RegisterStruct}
options={RegisterOptions}
value={this.state.formData}
onChange={formValue => this.onChangeFormRegister(formValue)}
/>

Related

Display search output using json data in react native

I am at a very primitive stage of learning react-native. And I am trying to solve a simple problem, which may sound silly, but I really want to know the answer.
I have a json file
data.js
export const PRODUCT_DATA = [
{
name: 'abc',
price: 90,
weight: '1 kg',
currency: 'INR',
liked: true,
image: require('../assets/images/carrots/Rectangle238.png')
},
{
name: 'bce',
price: 10,
weight: '1 kg',
currency: 'USD',
liked: false,
image: require('../assets/images/mango/Rectangle234.png')
},
{
AllCategoriesComponent: [
{
icon: "home-outline",
name: "Household",
shape: true,
},
{
icon: "basket-outline",
name: "Grocery",
shape: false,
},
{
icon: "ios-podium",
name: "Milk",
shape: true,
},
{
icon: "ios-rose",
name: "chilled",
shape: false,
},
{
icon: "hardware-chip",
name: "Drinks",
shape: true,
},
{
icon: "cloud",
name: "Pharmacy",
shape: true,
},
{
icon: "fast-food",
name: "Frozen Food",
shape: true,
},
{
icon: "football",
name: "Vegetable",
shape: true,
},
{
icon: "bulb",
name: "Meat",
shape: true,
},
{
icon: "football",
name: "Vegetable",
shape: true,
},
{
icon: "bulb",
name: "Meat",
shape: true,
},
]
},
];
ANd below is screen file
screen.js
import { SearchBar } from 'react-native-elements';
import { Text, View, TextInput } from 'react-native';
import React from 'react';
import { PRODUCT_DATA } from "./data";
export default class App extends React.Component {
constructor() {
super();
this.state = {
search: '',
}
}
updateSearch = (search) => {
this.setState({ search: search });
};
render() {
const { search } = this.state;
return (
<View>
<SearchBar onChangeText={this.updateSearch} value={search} />
{PRODUCT_DATA[2].AllCategoriesComponent.map((item, index) => {
if (item.name === this.state.search) {
return (
<View style={{ backgroundColor: "white" }}>
<Text>{search}</Text>
</View>
);
} else {
return (<Text></Text>);
}
})}
<Text>{this.state.search}</Text>
</View>
);
}
}
As you can see this is not a good solution. I am able to print the output only if I type full name in the SearchBar. Also it seems all the item.name are already on the screen, which comes up when value of search bar matches it. I want to start showing the output as soon as something is typed on the SearchBar
This might help please look into it
import { FlatList, Text, View, TextInput } from "react-native";
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
data: [],
};
this.arrayholder = [];
}
componentDidMount() {
const data = PRODUCT_DATA[2].AllCategoriesComponent.map((item, index) => {
return item;
});
this.setState({ data }, () => {
this.arrayholder = data;
});
}
searchData(text) {
const newData = this.arrayholder.filter((item) => {
const itemData = item.name.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
text: text,
});
}
render() {
return (
<View style={styles.MainContainer}>
<TextInput
onChangeText={(text) => this.searchData(text)}
value={this.state.text}
placeholder="Search Here"
/>
<FlatList
data={this.state.data}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => <Text style={styles.row}>{item.name}</Text>}
/>
</View>
);
}
}

What config and options do I need for react-native-highcharts to make a highstock OHLC graph?

I've been going through HighStock API to try and find which config and options I need to pass to the ChartView component in react-native-highcharts to draw my graph. I'm having a hard time finding what combination of config and options will get my desired result, things like series, dataGrouping, etc... . My data is a 2 dimensional array with 4 values for OHLC. My desired result is the photo at the top of this stackoverflow.
Here is my code so far.
class OHLC extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: "OHLC",
headerLeft: (
<TouchableOpacity
style={NavStyles.headerButton}
onPress={() => navigation.openDrawer()}>
<Icon name="bars" size={20} />
</TouchableOpacity>
),
})
render() {
var Highcharts='Highcharts';
var conf={
title: {
text: 'Stock Name'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Price'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
// tooltip: {
// formatter: function () {
// return '<b>' + this.series.name + '</b><br/>' +
// Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
// Highcharts.numberFormat(this.y, 2);
// }
// },
legend: {
enabled: false
},
// exporting: {
// enabled: false
// },
series: [{
type: 'ohlc',
name: 'AAPL Stock Price',
data: (function () {
let arrays = aExtractFromJson(data,'data', null,null);
arrays = ohlcExtractor(arrays);
return arrays;
// look at toFixed method for number to limit decimal point
}()),
dataGrouping: {
units: [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
};
const options = {
global: {
useUTC: false
},
lang: {
decimalPoint: ',',
thousandsSep: '.'
}
};
return (
<View>
<ChartView style={{height:300}} config={conf} options={options} stock={true} ></ChartView>
//To see if anything gets rendered.
<Text>HELLO DAVID!</Text>
</View>
);
}
}
After further research, I was able to find the config and options needed to create an OHLC Graph using the ChartView component in react-native-highcharts. I encountered some issues with rendering a blank screen so I added javaScriptEnabled={true} domStorageEnabled={true} originWhitelist={['']} to my ChartView.
In the config the essentials:
series with type: 'ohlc' and data: [[1,2,3,4],[2,3,4,5]] inside.
In options, no arguments are required, I left it as options='' in the ChartView.
Don't forget to add stock={true} in ChartView
My code, basic example:
import React, {Component} from 'react';
import {View} from 'react-native';
import ChartView from 'react-native-highcharts';
class OHLC extends React.Component {
constructor(props) {
super(props);
}
render() {
var Highcharts='Highcharts';
var conf={
chart: {
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
type: 'ohlc',
name: 'Random data',
/*Open, high,low,close values in a two dimensional array(two days)*/
data: [[1,2,3,4],[2,3,4,5]],
}]
};
return (
<View style={{borderRadius: 4, marginTop: 30,}}>
<ChartView style={{height:500}} config={conf} javaScriptEnabled={true} domStorageEnabled={true} originWhitelist={['']} stock={true} options=''></ChartView>
</View>
);
}
}

React Native Navigation - bottom tabs and drawer

I'm trying to add bottom tab bar in my jhipster ignite application, which uses react-native-navigation v2.
Screens are registered like:
Navigation.registerComponentWithRedux(LAUNCH_SCREEN, () => LaunchScreen, Provider, store)
Where e.g.:
export const LAUNCH_SCREEN = 'nav.LaunchScreen'
And here is the complete navigation:
export const topBar = {
title: {
text: 'MDNGHT',
color: Colors.snow
},
leftButtons: [
{
id: 'menuButton',
icon: Images.menuIcon,
testID: 'menuButton',
color: Colors.snow
}
]
}
export const launchScreenComponent = {
component: {
id: 'id.launch',
name: LAUNCH_SCREEN,
options: {
topBar: topBar,
bottomTab: {
fontSize: 12,
text: 'HOME'
}
}
}}
export const eventsScreenComponent = {
component: {
id: 'id.events',
name: EVENTS_SCREEN,
options: {
topBar: topBar,
bottomTab: {
fontSize: 12,
text: 'EVENTS'
}
}
}
}
export const bottomTabs = {
id: 'bottomTabs',
children: [
{
stack: {
children: [
launchScreenComponent
]
}
},
{
stack: {
children: [
eventsScreenComponent
]
}
}
],
options: {
bottomTabs: {
activeTintColor: 'red',
inactiveTintColor: 'grey',
backgroundColor: '#121212',
borderTopWidth: 0,
shadowOffset: {width: 5, height: 3},
shadowColor: 'black',
shadowOpacity: 0.5,
elevation: 5
}
}
}
export const appStack = {
root: {
sideMenu: {
left: {
component: {
name: DRAWER_CONTENT
}
},
center: {
bottomTabs: bottomTabs
}
}
}
}
Navigation.events().registerAppLaunchedListener(() => {
Navigation.setDefaultOptions({
topBar: {
topBar: {
title: {
color: Colors.snow
}
},
backButton: {
showTitle: false,
testID: 'backButton',
icon: Images.chevronLeftIcon,
color: Colors.snow,
iconColor: Colors.snow
},
background: {
color: Colors.background
}
},
sideMenu: {
left: {
enabled: false
}
}
})
Navigation.setRoot(appStack)
// handle app state and deep links
AppState.addEventListener('change', handleAppStateChange)
Linking.addEventListener('url', handleOpenURL)
})
I don't get any error message, my application just stops after start.
When I put:
stack: {
id: 'center',
children: [launchScreenComponent]
}
Instead of bottomTabs: bottomTabs in appStack, the application works (but without bottom tab bar)
Following the Layout docs from react-native-navigation, you can replace the appStack with a bottomTabs implementation instead of a drawer like below (only one tab configured as example, add another object in root.bottomTabs.children to add another tab).
export const appStack = {
root: {
bottomTabs: {
children: [
{
stack: {
id: 'firstTabStack',
children: [
{
component: {
name: LAUNCH_SCREEN,
options: {
topBar: {
title: {
text: 'Welcome!',
color: Colors.snow
}
}
}
}
}
],
options: {
bottomTab: {
iconColor: 'gray',
textColor: 'gray',
selectedIconColor: 'black',
selectedTextColor: 'black',
text: 'Launch Screen',
testID: 'LAUNCH_SCREEN',
icon: Images.menuIcon
}
}
}
}
]
}
}
}
It actually turns out that it is required to set an icon for each bottom tab, otherwise the app crashes:
bottomTab: {
fontSize: 12,
text: 'HOME'
icon: require('../shared/images/logo.png')
}
This resolves the issue.

Is it possible to set fixed widths on tables in material-table?

I'd like to be able to have fixed widths in my react table. I'm using this library material-table
import React from "react";
import MaterialTable from "material-table";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<MaterialTable
columns={[
{ title: "Name", field: "name" }, // 100px
{ title: "Surname", field: "surname" }, // set to 100px
{ title: "Birth Year", field: "birthYear", type: "numeric" }, // fill rest of row space
]}
data={[
{ name: "Mehmet", surname: "Baran", birthYear: 1987, birthCity: 63 },
{
name: "Zerya Betül",
surname: "Baran",
birthYear: 2017,
birthCity: 34
}
]}
title="Basic"
options={{
toolbar: false,
paging: false
}}
/>
);
}
Looks like you can use the headerStyle prop to set the widths.
import React from "react";
import MaterialTable from "material-table";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<MaterialTable
columns={[
{ title: "Name", field: "name", headerStyle: {width: "100px"} },
{ title: "Surname", field: "surname", headerStyle: {width: "100px"} },
{ title: "Birth Year", field: "birthYear", type: "numeric" },
]}
data={[
{ name: "Mehmet", surname: "Baran", birthYear: 1987, birthCity: 63 },
{
name: "Zerya Betül",
surname: "Baran",
birthYear: 2017,
birthCity: 34
}
]}
title="Basic"
options={{
toolbar: false,
paging: false
}}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

How to show top bar button with bottom tabs and side drawer

Im new to react native and react native navigation (v2) and been struggling with implementing a top nav button i.e. getting the top nav to show.
I wish to add a top bar with a button that can trigger the side drawer but cannot work out how to get the top nav to show.
Here is my working config of the bottom tabs and side draw:
const mainTabs = async () => {
Navigation.setRoot({
root: {
sideMenu: {
left: {
component: {
name: 'foo.SideDrawer',
},
},
center: {
id: 'MY_STACK',
bottomTabs: {
children: [
{
component: {
name: 'foo.HomeScreen',
options: {
bottomTab: {
fontSize: 12,
text: 'Home',
icon: await Icon.getImageSource("home", 30)
}
}
},
},
{
component: {
name: 'foo.ProfileScreen',
options: {
bottomTab: {
text: 'Profile',
fontSize: 12,
icon: await Icon.getImageSource("person", 30)
}
}
},
}
]
}
}
}
}
})
};
Can anyone advise where the top bar and button config should go?
--
EDIT 1 - Home screen component:
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class HomeScreen extends Component {
static get options() {
return {
topBar: {
title: {
text: 'Home',
},
leftButtons: [
{
icon: require('../../assets/signin.png'),
text: 'Button one',
id: 'homeButton',
},
],
},
};
}
render () {
return (
<View style={styles.container}>
<Text>Home Screen</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F0EFE8'
}
})
export default HomeScreen;
You add this static function in your component
export default class HomeScreen extends Component {
static get options() {
return {
topBar: {
title: {
text: 'Home',
},
leftButtons: [
{
icon: require('../../../assets/icons/icon.png'),
id: 'homeButton',
},
],
},
};
}
}
and here you find all needed configs https://wix.github.io/react-native-navigation/#/docs/topBar-buttons