React Native - can I set dynamic initial state? - react-native

let say I have a state like this:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1'
}
}
}
and then I setState the FirstTime to add another key/value:
this.setState({FirstTime: {...this.state.FirstTime, bar: 'ex2'}})
there's a way to change the initial state to be like this:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1',
bar: 'ex2'
}
}
}
when I reloaded the apps?

Try something like this
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
FirstTime: {
foo: 'ex1'
}
}
}
render() {
console.log(this.state.FirstTime); //Sorry a typo found in this line
return (
<div>Hey</div>
);
}
componentDidMount() {
let obj = {
bar: 'ex2'
}
let finalData = { ...this.state.FirstTime, ...obj }
this.setState({ FirstTime: finalData })
}
}
const rootElement = document.getElementById("root")
ReactDOM.render(
<App />,
rootElement
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Related

Children calling grandparent function

I have a box containing a list. The list is made of todoItems. A delete button is next to each item. The button should call the delete method of the box class. Should I pass it to the class List first? Can I call directly the method in the class Box?
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e)
{
const todoItemId = this.props.todoItemId;
if (!todoItemId)
{
return;
}
this.props.onTodoItemDeleteList({ todoItemId: todoItemId });
}
render() {
return (
<div className="todoItem">
<button onClick={() => this.handleClick()}>delete</button>;
</div>
);
}
}
My List: here the onTodoItemDeleteList is seen in the console, but appears as undefined.
class TodoItemList extends React.Component {
constructor(props) {
super(props);
this.handleItemDeleteList = this.handleItemDeleteList.bind(this);
}
handleItemDeleteList(todoItemId)
{
//call handleItemDelete
}
render() {
if (this.props.data)
{
var todoItemNodes = this.props.data.map(function (todoItem){
return (
<TodoItem todoItemId={todoItem.todoItemId} onTodoItemDeleteList={this.handleItemDeleteList} key={todoItem.todoItemId}>
</TodoItem>
);
});
}
return <div className="todoItemList">{todoItemNodes}</div>;
}
}
My Box: this is where I handle my ajax call to the server.
class TodoItemBox extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
this.handleItemDelete = this.handleItemDelete.bind(this);
}
handleItemDelete(todoItemId) {
const data = new FormData();
data.append('todoItemId', todoItemId);
const xhr = new XMLHttpRequest();
xhr.open('post', this.props.deleteUrl, true);
xhr.onload = () => this.loadTodoItemsFromServer();
xhr.send(data);
}
render() {
return (
<div className="todoItemBox">
<TodoItemList data={this.state.data} />
</div>
);
}
}
I solved it by using arrow function in the parent too, it looks like this:
onTodoItemDeleteList={ (todoItemId) => handleItemDeleteList(todoItemId)}
and in the constructor:
handleItemDeleteList = this.handleItemDeleteList.bind(this);

React Native : How to get device Screen Brightness and render it

I`m creating an React App to display device Info. I want to render Screen Brightness level, not in Console. How do I do it?
DeviceBrightness.getSystemBrightnessLevel().then(function(luminous) {
console.log(luminous)
})
I expected to render the screen brightness level, not to display in console
import DeviceBrightness from 'react-native-device-brightness';
export default class App extends Component{
constructor(props){
super(props);
this.state = {
isLoaded: false,
brightness: 0,
};
}
componentWillMount() {
DeviceBrightness.getSystemBrightnessLevel()
.then((luminous) =>{
this.setState({
brightness: luminous,
isLoaded: true,
});
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.instructions}>{this.state.brightness}</Text>
</View>
);
}
}
import DeviceBrightness from 'react-native-device-brightness';
export default class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
brightness: 0
};
}
componentDidMount() {
DeviceBrightness.getSystemBrightnessLevel()
.then(luminous => {
this.setState({
brightness: luminous,
isLoaded: true,
});
});
}
render() {
const { isLoaded, brightness } = this.state;
if (!isLoaded) {
return {/*loading view*/}
} else {
return (
<Text>{brightness}</Text>
);
}
}
}

Start a countdown timer with react-natiev

I want to have a countdown component for my project. I tried by setting setInterval, but I have a requirement to pause and continue the timer. So How can I achieve this?
I created a jsfiddle with a simple demonstration of how it can be done: https://jsfiddle.net/69z2wepo/258601/. Written using React but the principle is exactly the same with React Native.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 10,
};
this.interval = null;
this.cleanUp = this.cleanUp.bind(this);
this.decreaseCounter = this.decreaseCounter.bind(this);
this.startCounter = this.startCounter.bind(this);
}
componentWillUnmount() {
cleanUp();
}
cleanUp() {
clearInterval(this.interval);
}
decreaseCounter() {
if (this.state.counter === 0) {
return this.cleanUp();
}
this.setState({counter: this.state.counter - 1});
}
startCounter() {
this.interval = setInterval(this.decreaseCounter, 1000);
}
render() {
return (
<div>
<button onClick={this.startCounter}>Start</button>
Counter {this.state.counter}
<button onClick={this.cleanUp}>Stop</button>
</div>
);
}
}

Setting state with a function in another file

Without attempting to update my state, the initial location in state is presented correctly. When I set state using a helper function, nothing is displayed in my app. What am I doing wrong? Additionally, logging props inside ShowLocation's render() shows that the coords{lat:xx,long:xx} are coming through correctly.
App.js
import * as helpers from './src/helpers';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = globals.initial_state;
}
componentDidMount(){
this.setState({location:helpers.getLocation()});
}
render() {
return (
<View>
<ShowLocation coords={this.state.location} />
</View>
);
}
}
ShowLocation.js
class ShowLocation extends Component {
constructor(props){
super(props);
}
render(){
return(
<View>
<Text>{this.props.coords.lat}, {this.props.coords.long}</Text>
</View>
)
}
};
helpers.getLocation:
export function getLocation(){
coords = {};
navigator.geolocation.getCurrentPosition(
(position) => {
coords['lat'] = position.coords.latitude
coords['long'] = position.coords.longitude
},
(error) => this.setState({ navigatorError: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
return coords;
}
Did you tried:
componentDidMount(){
this.setState({ location: getLocation().bind(this) });
}
Or, same thing, but cleaner code:
constructor() {
// other stuff
this.getLocation = getLocation().bind(this)
}
componentDidMount(){
this.setState({ location: this.getLocation() });
}
Edit:
You must import { getLocation} from 'path/of/file'

React Native: Move component in view hierarchy

How can a component be moved from one part of the render hierarchy to another while maintaining component state? In the example below, the result of the call to setView creates a new view (as seen by a new instanceValue number), even though I pass what looks like the existing view.
class TestTo extends React.Component {
constructor(props) {
super(props);
this.state = {
instanceValue: parseInt(Math.random() * 100)
}
}
render() {
return <Text>{this.state.instanceValue}</Text>
}
}
class TestFrom extends React.Component {
constructor(props) {
super(props);
this.state = {
view: <TestTo />
}
}
doSet = () => {
this.props.nav.setView(this.state.view);
}
render() {
return <View>
<Button title="doaction" onPress={this.doSet} />
{this.state.view}
</View>
}
}
class Holder extends React.Component {
constructor(props) {
super(props);
this.state = {
view: <TestFrom nav={this} />
}
}
setView = (view) => {
this.setState({view: view});
}
render() {
return this.state.view
}
}
<Holder />