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);
Related
`
import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { useState } from "react";
import {useRef,createRef} from 'react';
import { useEffect } from 'react';
import { Dimensions } from 'react-native';
const windowWidth = Dimensions.get('window').width;
export default function App() {
const [selectedId, setSelectedId] = useState(null);
const elementsRef = useRef(persons.map(() => createRef()));
const [y, setY] = useState(false);
return (
<View style={{
flex:1,
justifyContent:'center',
alignItems:'center',
}}>
<ScrollView contentContainerStyle={{
paddingHorizontal:20
}}>
<View>
{persons.map((person, index) => {
const backgroundColor = person.id === selectedId ? "#6e3b6e" : "#f9c2ff";
const onPress = (newRef) => {
newRef?.current?.measureInWindow( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
setY(fy)
})
setSelectedId(person.id)
}
return (
<TouchableOpacity
ref={elementsRef?.current[index]}
key={person.id}
style={{
backgroundColor:backgroundColor,
marginBottom:20,
height:200,
justifyContent:'center',
alignItems:'center',
width: windowWidth-40
}}
onPress={() => onPress(elementsRef?.current[index])} >
<Text>{person.name}</Text>
<Text>{y}</Text>
</TouchableOpacity>
);
})}
</View>
</ScrollView>
</View>
);
}
const persons = [
{
id: "1",
name: "Earnest Green",
},
{
id: "2",
name: "Winston Orn",
},
{
id: "3",
name: "Carlton Collins",
},
{
id: "4",
name: "Malcolm Labadie",
},
{
id: "5",
name: "Michelle Dare",
},
{
id: "6",
name: "Carlton Zieme",
},
{
id: "7",
name: "Jessie Dickinson",
},
{
id: "8",
name: "Julian Gulgowski",
},
{
id: "9",
name: "Ellen Veum",
},
{
id: "10",
name: "Lorena Rice",
},
{
id: "11",
name: "Carlton Zieme",
},
{
id: "12",
name: "Jessie Dickinson",
},
{
id: "13",
name: "Julian Gulgowski",
},
{
id: "14",
name: "Ellen Veum",
},
{
id: "15",
name: "Lorena Rice",
},
];
`
Open code in Expo Snack > https://snack.expo.dev/#stefanosalexandrou/d6a238
I create a list with Map method. Every item in screen is selectable. When Item selected then background of selected item changed. Also the code get the Y position of item in window screen.
What I want:
I want when click item, the selected item from start Y position move/scroll to the middle of ScrollView.
Like this> https://www.youtube.com/shorts/XqX0x9OzN8M,
https://www.youtube.com/shorts/an2_Dih-D8g
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>
);
}
}
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>
);
}
}
I want to select the selected items which i already select & save at backend after that if i get response then set already selected those items which i have set in react native multi select
here is my code for react native multiselect
//Example Multiple select / Dropdown / Picker in React Native
import React, { Component } from "react";
//Import React
import { View, Text, Picker, StyleSheet, SafeAreaView } from "react-native";
//Import basic react native components
import MultiSelect from "react-native-multiple-select";
//Import MultiSelect library
//Dummy Data for the MutiSelect
this.items = [
{ id: "1", name: "America" },
{ id: "2", name: "Argentina" },
{ id: "3", name: "Armenia" },
{ id: "4", name: "Australia" },
{ id: "5", name: "Austria" },
{ id: "6", name: "Azerbaijan" },
{ id: "7", name: "Argentina" },
{ id: "8", name: "Belarus" },
{ id: "9", name: "Belgium" },
{ id: "10", name: "Brazil" }
];
export default class App extends Component {
state = {
//We will store selected item in this
selectedItems: [
{ id: "1", name: "America" },
{ id: "2", name: "Argentina" },
{ id: "3", name: "Armenia" },
{ id: "4", name: "Australia" }
]
};
onSelectedItemsChange = selectedItems => {
this.setState({ selectedItems });
//Set Selected Items
};
render() {
const { selectedItems } = this.state;
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, padding: 30 }}>
<MultiSelect
hideTags
items={items}
uniqueKey="id"
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Pick Items"
searchInputPlaceholderText="Search Items..."
onChangeInput={text => console.log(text)}
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{ color: "#CCC" }}
submitButtonColor="#48d22b"
submitButtonText="Submit"
/>
<View>
{this.multiSelect &&
this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
</View>
</SafeAreaView>
);
}
}
Got it.
this.state={
selectedData: "158" // list of id here(without space, that is your response of api)
};
<MultiSelect
.....
.....
selectedItems={selectedData}
/>
<View>
{this.multiselect ? this.multiSelect.getSelectedItemsExt(selectedData): null}
</View>
I had this same issue and I figured out how to preset selections by using parts of the accepted answer.
I learned that selectedItems is a list of whatever is set as the uniqueKey in the MultipleSelect props.
For example, if you put the uniqueKey as a numbered id of each list member and you wanted the second member set as selected, you would have selectedItems = {[ "2" ]}
I hope this makes sense.
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)}
/>