With this code the table is getting populated. I am trying to load new data to the table on clicking the button "Load New Data" which will call "handleClick" handler and I am loading new data "this.state.MyDataList = require('./data1.json');" but the actual table is showing the same old data. Why the new data is not getting reflected in the table.
import React, {Component} from 'react';
import 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min.css';
import 'react-bootstrap-table2-filter/dist/react-bootstrap-table2-filter.css'
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter , selectFilter} from 'react-bootstrap-table2-filter';
import ToolkitProvider, { Search } from 'react-bootstrap-table2-toolkit';
import axios from 'axios';
const { SearchBar } = Search;
export default class Customers extends Component {
constructor(props) {
super(props)
this.state = {MyDataList: require('./data.json'),
"columns" : [{
dataField: 'id',
text: 'Title',
sort: true,
filter: textFilter()
},{
dataField: 'name',
text: name',
sort: true,
filter: textFilter()
},{
dataField: 'age',
text: 'Age'
}]};
}
//function which is called the first time the component loads
componentDidMount() {
}
handleOnExpand = (row, isExpand, rowIndex, e) => {
//My code here
}
**handleClick = () => {
this.state.MyDataList = require('./data1.json');
}**
handleDataChange = ({ dataSize }) => {
this.data = require('./data1.json');
console.log("Hi")
}
render() {
// if (!this.state.MyDataList)
// return (<p>Loading data</p>)
return (<div className="addmargin">
<ToolkitProvider
keyField="Id"
data={ this.state.MyDataList }
columns={ this.state.columns }
search
>
{
props => (
<div>
<h3>Input something at below input field:</h3>
<SearchBar keyField='Id' data={ this.state.MyDataList } columns={ this.state.columns }/>
<hr/>
**<button className="btn btn-warning" onClick={ this.handleClick }>Load New Data</button>**
<BootstrapTable onDataSizeChange={ this.handleDataChange } bootstrap4 keyField='Id' data={this.state.MyDataList } columns={ this.state.columns } striped hover condensed filter={ filterFactory() } />
</div>
)
}
</ToolkitProvider>
</div>
);
}
}
It worked after loading data with the state setter " this.setState".
handleClick = () => {
this.setState({MyDataList : require('./data1.json') })
}
Related
This is my code. I am not sure what error exists.
When I click the image button, it calls proper function exactly.
If I click the first button, it calls toggleBooks() function correctly.
Then in that function, I want to use vidMute state value.
So I tried console.log('Video toggle', this.state.vidMute); then it gives me an error like the following image.
But if I print console.log('Video toggle'), then it works well.
How to use state value in that function?
export default class Video extends Component {
constructor(props) {
super(props)
this.state = {
vidMute: false,
audioShow: false,
callShow: false,
btn: [
{ func: this.toggleAudio, url: magic, de_url: de_magic },
{ func: this.endCall, url: endcall, de_url: de_endcall },
{ func: this.toggleBooks, url: camerarotate, de_url: de_camerarotate },
],
};
this.toggleAudio = this.toggleAudio.bind(this)
this.endCall = this.endCall.bind(this)
this.toggleBooks = this.toggleBooks.bind(this)
}
toggleBooks() {
console.log('Video toggle', this.state.vidMute);
}
endCall() {
console.log('Call toggle', this.state.audioShow);
}
toggleAudio() {
console.log('Audio toggle', this.state.callShow);
}
render() {
return (
<View>
{
this.state.btn.map((item, index) => (
<TouchableOpacity key={index} style={styles.iconStyle} activeOpacity={0.4} onPress={item.func}>
<Image source={this.state.lockState ? item.de_url : item.url} style={{ width: 70, height: 70 }} />
</TouchableOpacity>
))
}
</View>
)
}
}
this refers to the context of your function and not the context of your component. You can try to bind your method like this :
this.myMethod = this.myMethod.bind(this);
in your constructor.
Or use the fat arrow pattern (Highly recommanded) which automatically includes the binding to your component's context.
Here is a binding example on stackblitz
Here is the code :
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
items:[
{name:"item 1", func: () => this.test()},
{name:"item 2", func: () => this.test2()}
]
};
this.test = this.test.bind(this);
}
test() {
console.log('Hi', this.state.name);
}
test2() {
console.log('Hello', this.state.name); // Note this is not binded
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p onClick={this.test}>
Start editing to see some magic happen :)
</p>
<div>
{
this.state.items.map(item => <div onClick={() => item.func()}>{item.name}</div>)
}
</div>
</div>
);
}
}
render(<App />, document.getElementById('root'));
I am trying to use a multi select drop down as explained here but one way or the other the items array is not properly defined.
This is my code for the friendselector component:
/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {View} from 'react-native';
import MultiSelect from 'react-native-multiple-select';
export default class FriendSelector extends Component {
constructor() {
super();
this.state = {
selectedItems: [],
items: [
{
id: '92iijs7yta',
name: 'Kenneth',
},
{
id: 'a0s0a8ssbsd',
name: 'Ann',
},
{
id: '16hbajsabsd',
name: 'Leen',
},
{
id: 'nahs75a5sg',
name: 'Kris',
},
{
id: '667atsas',
name: 'Steve',
},
{
id: 'suudydjsjd',
name: 'Sarah',
},
],
};
}
onSelectedItemsChange = selectedItems => {
this.setState({selectedItems});
};
render() {
const {selectedItems} = this.state;
return (
<View>
<MultiSelect
hideTags
items={this.items}
uniqueKey="id"
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Pick friend(s)"
searchInputPlaceholderText="Search..."
onChangeInput={text => console.log(text)}
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{color: '#CCC'}}
submitButtonColor="#CCC"
submitButtonText="Submit"
/>
<View>
{this.multiSelect &&
this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
</View>
);
}
}
which is similar as in this tutorial, I did change some references to items with state - this to connect things to one another. Still the items are not loaded in items={this.items} I have the feeling.
Does anyone know why?
This is the error:
Thanks for your answer!
items prop is getting an undefined value because it's assigned this.items which doesn't exist in your class.
Change items={this.items} to items={this.sate.items} it makes more sense.
Another solution is to declare items array outside of the state.
The App is simple.. Conversion of gas.. What im trying to do is multiply the Inputed Amount by 2 as if it is the formula. So i have a index.js which is the Parent, and the Calculate.component.js who do all the calculations. What i want is, index.js will pass a inputed value to the component and do the calculations and pass it again to the index.js to display the calculated amount.
Index.js
import React, { Component } from 'react';
import { Text } from 'react-native';
import styled from 'styled-components';
import PickerComponent from './Picker.Component';
import CalculateAVGAS from './Calculate.component';
export default class PickerAVGAS extends Component {
static navigationOptions = ({ navigation }) => ({
title: navigation.getParam('headerTitle'),
headerStyle: {
borderBottomColor: 'white',
},
});
state = {
gasTypeFrom: 'Gas Type',
gasTypeTo: 'Gas Type',
input_amount: '',
pickerFrom: false,
pickerTo: false,
isResult: false,
result: '',
};
inputAmount = amount => {
this.setState({ input_amount: amount });
console.log(amount);
};
onResult = value => {
this.setState({
result: value,
});
console.log('callback ', value);
};
render() {
return (
<Container>
<Input
placeholder="Amount"
multiline
keyboardType="numeric"
onChangeText={amount => this.inputAmount(amount)}
/>
<ResultContainer>
<ResultText>{this.state.result}</ResultText>
</ResultContainer>
<CalculateContainer>
<CalculateAVGAS
title="Convert"
amount={this.state.input_amount}
total="total"
titleFrom={this.state.gasTypeFrom}
titleTo={this.state.gasTypeTo}
// isResult={this.toggleResult}
result={value => this.onResult(value)}
/>
</CalculateContainer>
</Container>
);
}
}
CalculateAVGAS / component
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
export default class CalculateAVGAS extends Component {
static propTypes = {
amount: PropTypes.string.isRequired,
titleFrom: PropTypes.string.isRequired,
titleTo: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
};
state = {
totalVisible: true,
result: '',
};
onPressConversion = () => {
const formula = this.props.amount * 2;
const i = this.props.result(this.state.result);
this.setState({ result: formula });
// console.log(this.state.result);
console.log('func()');
}
render() {
return (
<ButtonContainer onPress={() => this.onPressConversion()}>
<ButtonText>{this.props.title}</ButtonText>
</ButtonContainer>
);
}
}
After doing this, the setState only updates when pressing the Convert button twice
your issue here is that you want to display information in the parent component, but you are saving that info in the child component's state.
Just pass amount, and result, to the stateless child component (CalculateAVGAS).
It's usually best to keep child components "dumb" (i.e. presentational) and just pass the information they need to display, as well as any functions that need to be executed, as props.
import React, {Component} from 'react';
import styled from 'styled-components';
export default class CalculateAVGAS extends Component {
onPressConversion = () => {
this.props.result(this.props.amount * 2);
};
render() {
return (
<ButtonContainer onPress={() => this.onPressConversion()}>
<ButtonText>{this.props.title}</ButtonText>
</ButtonContainer>
);
}
}
const ButtonContainer = styled.TouchableOpacity``;
const ButtonText = styled.Text``;
Parent component looks like:
import React, {Component} from 'react';
import {Text} from 'react-native';
import styled from 'styled-components';
import CalculateAVGAS from './Stack';
export default class PickerAVGAS extends Component {
static navigationOptions = ({navigation}) => ({
title: navigation.getParam('headerTitle'),
headerStyle: {
borderBottomColor: 'white',
},
});
state = {
gasTypeFrom: 'Gas Type',
gasTypeTo: 'Gas Type',
input_amount: null,
pickerFrom: false,
pickerTo: false,
isResult: false,
result: null,
};
inputAmount = amount => {
this.setState({input_amount: amount});
};
onResult = value => {
this.setState({
result: value,
});
};
render() {
return (
<Container>
<Input
placeholder="Amount"
multiline
keyboardType="numeric"
onChangeText={amount => this.inputAmount(amount)}
/>
<ResultContainer>
<ResultText>{this.state.result}</ResultText>
</ResultContainer>
<CalculateContainer>
<CalculateAVGAS
title="Convert"
amount={this.state.input_amount}
total="total"
titleFrom={this.state.gasTypeFrom}
titleTo={this.state.gasTypeTo}
result={value => this.onResult(value)}
/>
</CalculateContainer>
</Container>
);
}
}
const Container = styled.View``;
const ResultContainer = styled.View``;
const ResultText = styled.Text``;
const CalculateContainer = styled.View``;
const Input = styled.TextInput``;
How do I uncheck all checkbox if the data is no preference? I don't know how to manipulate the data.
This is the index.js:
import React, { Component } from "react";
import { Text, View } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Colors } from '../../../themes/';
import style from "./style";
class CCheckBox extends React.Component {
/////////////////////////////
// constructor()
/////////////////////////////
constructor(props, context) {
super(props, context);
console.log('custom/ccheckbox/index.js constructor()');
this.state = {
checked: false,
};
}
/////////////////////////////
// handleCheck()
/////////////////////////////
handleCheck() {
this.setState({ selectedCheckbox }); // update selected item
}
render() {
return (
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked}
containerStyle={style.content}
onPress={() => this.handleCheck()}
/>
);
}
}
export default CCheckBox;
And this is my profalcoholpref.js:
import React, { Component } from "react";
import { ScrollView, View } from 'react-native';
import { Content } from 'native-base';
import CButton from '../cbutton/index';
import PopSelectList from './popselectlist';
import styleC from "../../common/style";
import style from "./style";
class PopAlcoholPref extends React.Component {
///////////////////////////////
// constructor()
///////////////////////////////
constructor(props, context) {
super(props, context);
console.log('custom/cfield/popalcoholpref.js constructor()');
this.state = {
selectedCheckbox: {},
visible: this.props.visible,
data: [
{
id : 1,
code : 'DON',
description : 'Do not drink',
},
{
id : 2,
code : 'INF',
description : 'Infrequently',
},
{
id : 3,
code : 'SOC',
description : 'Socially',
},
{
id : 4,
code : 'MOD',
description : 'Moderately',
},
{
id : 5,
code : 'ASN',
description : 'As Needed',
},
{
id : 5,
code : 'NOP',
description : 'No Preference',
},
]
};
}
///////////////////////////////
// componentWillReceiveProps()
///////////////////////////////
componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps()');
this.setState({
visible: nextProps.visible
});
}
///////////////////////////////
// handleSave()
///////////////////////////////
handleSave() {
console.log('handleSave()');
this.setState({
visible: false
});
}
///////////////////////////////
// render()
///////////////////////////////
render() {
return (
<View>
<PopSelectList title='Alcohol Preference' data={this.state.data} visible={this.state.visible} handleSave={() => this.handleSave()} />
</View>
);
}
}
export default PopAlcoholPref;
How do I uncheck all other checkbox if no preference is checked? Is there any way I can manipulate the data? Index.js is the frontend and I manipulated the checkbox there and in the prefalcohol is where the data is being stored.
You will need a bit of a refactoring here I beleive.
You should move the state handling logic to the list. In the list you can manipulate all the checkboxes at the same time.
class List extends Component {
constructor(props) {
super(props);
this.state = {
checkBoxesList: [{
id: 1,
checked: false,
}, {
id: 2,
checked: false,
}]
}
}
unCheckAll() {
this.setState({ checkBoxesList: this.state.checkBoxesList.map(({ id }) => ({
id: id,
checked: false,
})) })
}
checkBoxSelected(id) {
const index = this.state.checkBoxesList.findIndex((value) => value.id === id);
this.setState({ checkBoxesList[index]: {
...this.state.checkBoxesList[index],
checked: !this.state.checkBoxesList[index].checked
})
}
renderCheckBoxes() {
return this.state.checkBoxesList.map(({id, checked}) => (
<CheckBox id={id} checked={checked} onPress={this.checkBoxSelected} />
))
}
render() {
return (
<View>
{this.renderCheckBoxes()}
</View>
)
}
}
So this Component handles the states for the checkboxes. You need to make sure that you also implement the callback inside the CheckBox component for the OnPress method. Now calling the UncheckAll method will uncheck all the checkboxes.
But also you have to put in some extra check before setting the checkBoxesList if the index does exist.
I've tried to change the radio value in ReactNative App with NativeBase template. I want to get or set value from the radio after click it, exactly checked or not. But couldn't find a way to get or set value to it. Even the radio button never changed on the screen after click. The codes are like as below:
import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import {
Container,
Header,
Title,
Content,
Text,
Button,
Icon,
InputGroup,
Input,
List,
ListItem,
Radio, } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import { Col, Row, Grid } from 'react-native-easy-grid';
import styles from './styles';
import dimension from './global';
import Swiper from 'react-native-swiper';
const imgBoy = require('../../../images/icon_boy.png');
const imgGirl = require('../../../images/icon_girl.png');
const {
popRoute,
} = actions;
class SessionPage extends Component {
static propTypes = {
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
constructor(props) {
super(props);
// console.log(this.props.navigation);
this.state = {
sliderCount : parseInt(this.props.navigation.behavior.length / 5) + 1,
sliderArray : [],
selected : false,
}
this.getSliderArray();
console.log(this.state);
}
getSliderArray() {
for (var i = 0; i < this.state.sliderCount; i++) {
var childArray = [];
for (var j = i * 5; j < 5 * (i + 1); j++) {
if (this.props.navigation.behavior[j] != null){
var unit = this.props.navigation.behavior[j];
unit.selected = true;
childArray.push(unit);
}
}
this.state.sliderArray.push({
index : i,
behaviors : childArray
})
}
}
selectRadio(i, j){
this.state.sliderArray[i].behaviors[j].selected = true;
}
render() {
const { props: { name, index, list } } = this;
return (
<Container style={styles.container}>
<Swiper style={styles.wrapper}
height={dimension.Height - 400}
width={dimension.Width - 40}
showsButtons={false}
showsPagination={true}>
{this.state.sliderArray.map((item, i) =>
<View style={styles.slide1} key={i}>
{item.behaviors.map((subitem, j) =>
<ListItem key={i + "-" + j} style={styles.cardradio}>
<Radio selected={this.state.sliderArray[i].behaviors[j].selected} onPress={() => this.selectRadio(i, j)} />
<Text>{subitem.behaviorName}</Text>
</ListItem>
)}
</View>
)}
</Swiper>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
});
export default connect(mapStateToProps, bindAction)(SessionPage);
selectRadio(i, j){
this.state.sliderArray[i].behaviors[j].selected = true; <== This is the problem
}
When you call this.state = something after the component has mounted, it doesn't trigger update method of component life cycle. Hence view will not be updated.
You should be using this.setState() to update your views
this.setState({
slider = something
})
For more info, refer docs
this.setState() is an async method. After you make changes in getSliderArray(), it may not be reflected in immediate console.log
this.getSliderArray();
console.log(this.state);
You can pass callback to this.setState() to perform any action only after state is changed
this.setState({
// new values
}, function() {
// Will be called only after switching to new state
})