Invisible changes when screen update - javascript

I'm new in react-native and have some probems. In the fahterScreen I add some items to array and pass to childs as prop, I need that the child (CanastaScreen) update every 1seg and show the new value. I have the next code:
export default class CanastaScreen extends React.Component {
constructor(props) {
super(props);
setInterval( () => { this.render(); }, 1000);
};
render() {
return (
<Container>
<Content>
{this.props.screenProps.canasta.map( (item) => {
console.log(item.nombre);
return (
<Text>{item.nombre}</Text>
);
})}
</Content>
</Container>
);
}
}
Console output show correctly:
Item1
Item2
Item3
etc.
But the screen is always in blank. Some can help my about it ?
Thanks

First of all, you never should call render method of a component. in React Native, a component should update only if it's state changes. so if you have something like this :
<Parent>
<Canasta> ... </Canasta>
</Parent>
assuming that the changing variable is called foo in state of Parent, you need to pass it as prop to Canasta (child) and now by changing state of Parent (changing foo), Canasta should get updated. here's an example (calling updateFoo will update both Parent and Canasta):
class Parent extends Component {
constructor(props){
super(props); // it's recommended to include this in all constructors
this.state = { foo: initalValue } // give some value to foo
}
updateFoo(newValue){
this.setState({foo: newValue}) // setting state on a component will update it (as i said)
}
render() {
return(
<Canasta someProp={this.state.foo}> ... </Canasta>
)
}
}
}

After various changes, is found, the complete structure is: Parent(App.js) call children(Menu, Canasta). Menu allow add items to the shop-car and Canasta allow to sort and delete items. These are the important parts of the code:
App.js
export default class App extends React.Component {
constructor(props) {
super(props);
this.stateUpdater = this.stateUpdater.bind(this);
this.state = { canasta:[] };
}
render() {
return (
<View>
<RootNavigation data={[this.state, this.stateUpdater]} />
</View>
);
}
}
Menu.js
tryAddCanasta(index, plato){
let canasta = this.props.screenProps[0].canasta;
plato.id_Plato = canasta.length;
canasta.push(plato);
this.props.screenProps[1]('canasta', canasta);
}
Canasta.js
shouldComponentUpdate(nextProps, nextState) {
return true;
}
render() {
return (
<Container>
<Content>
<List>
{this.props.screenProps[0].canasta.map( (item) => {
return ( this._renderRow(item) );
})}
</List>
</Content>
</Container>
);
}
Special thanks to #Shadow_m2, now I don't need check every time, it works in "real time"

Related

ReactJS: passing function to child component results in TypeError

I'm trying to pass a callback function from parent->child, but when the child component is rendered I get the error: TypeError: this.props.setCurrentWindow is not a function.
Parent component where I am trying to pass the function setCurrentWindow
class Parent extends Component {
constructor(props){
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow(){
console.log("called")
}
render(){
return(
<Child
setCurrentWindow={this.setCurrentWindow}
/>)}
}
child component where I am trying to call setCurrentWindow
class Child extends Component{
constructor(props){
super(props)
}
render(){
return(
<div
onClick={()=>{this.props.setCurrentWindow()}}>
{this.props.children}
</div>
)}
}
Why is setCurrentWindow not being recognized as a function here?
Please check this example where I only found the difference is to have child element like <div><h1>Hello</h1></div> that was not in your code. other than this everything is working fine. When I click on the div, it writes called in console
export default class Parent extends Component {
constructor(props) {
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow() {
console.log("called")
}
render() {
return (
<Child
setCurrentWindow={this.setCurrentWindow}
>
<div>
<h1>Hello</h1>
</div>
</Child>
)
}
}
class Child extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div onClick={() => {
this.props.setCurrentWindow()
}}>
{this.props.children}
</div>
);
}
}
Try this:
parent.jsx:
class Parent extends Component {
// code omitted for brevity
handleSetWindow = () => {
//
};
render() {
return (
<div>
<Child onSetWindow={this.handleSetWindow}
/>
</div>
);
}
}
child.jsx:
class Child extends Component {
render() {
return (
<div>
<button onClick={() => this.props.onSetWindow()} >
Set
</button>
</div>
);
}
}
A stupid answer but the final solution here is that not all instances of my child components were being passed this.setCurrentWindow hence the undefined error. Durrr! Thanks for the responses!

How to pass class props to function in reactjs

I am attempting to pull the value of Number from the props set in the Button class. And then render this value in the discover function. The class is correctly displaying the value of Number. However, the function is not displaying any value for Number.
I have been messing around with this for a while to get it to work. But I cannot find any solutions to my problem.
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
Number: "55"
};
}
render() {
return (
<div>
<p>Number: {this.state.Number}</p> //The value of Number is displayed on the page
</div>
);
}
};
const discover = (props) => {
return (
<div>
<Button />
<p>Number: {props.Number}</p> //The value of Number is not displayed
</div>
);
};
export default discover;
There are no error messages.
Expected result shown:
https://i.imgur.com/fr61SE0.png
Actual result shown:
https://i.imgur.com/MRE0Lsj.png
You want to keep discover and button in sync with eachother, but currently there isn't anything doing that. button is a child of discover with a local state. Instead of this make the parent have the state and it can then pass that down to the button component.
class Discover extends Component {
state = { number: 55 }
render() {
const { number } = this.state
return (
<div>
<Button number={number} />
<p>Number: {number}</p>
</div>
);
}
};
const Button = ({number) => {
return (
<div>
<p>Number: {number}</p>
</div>
);
}
};
export default Discover;
Here's a live example for you to play with
Your discover is a functional component and you are not passing anything to your component and in your button component, you are setting state that is the reason behind your output. try this.
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
Number: "55"
};
}
render() {
return (
<div>
<p>Number: {this.state.Number}</p> //The value of Number is displayed on the page
<discover {...this.state} />
</div>
);
}
};
const discover = (props) => {
return (
<div>
<p>Number: {props.Number}</p> //The value of Number is not displayed
</div>
);
};
export default Button;
now you will get your desire output
I'm not sure where you are calling the Discover component, but you would need to pass the number down as a prop to the Discover component in order to get it to render.
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
Number: "55"
};
}
render() {
return (
<div>
<p>Number: {this.state.Number}</p> //The value of Number is displayed on the page
<Discover Number={this.state.Number}/> // we are passing Number as a prop to the Discover component
</div>
);
}
};
const Discover = (props) => {
return (
<div>
<Button />
<p>Number: {props.Number}</p> //The value of Number is not displayed
</div>
);
};
export default Discover;
I'd also capitalize your custom react components like Discover.
Why do components in react need to be capitalized?

Stop Relay: Query Renderer in reloading data for certain setStates

I'm currently following this and I did get it to work. But I would like to know if there is a way to stop the Query Render from reloading the data when calling this.setState(). Basically what I want is when I type into the textbox, I don't want to reload the data just yet but due to rendering issues, I need to set the state. I want the data to be reloaded ONLY when a button is clicked but the data will be based on the textbox value.
What I tried is separating the textbox value state from the actual variable passed to graphql, but it seems that regardless of variable change the Query will reload.
Here is the code FYR.
const query = graphql`
query TestComponentQuery($accountId: Int) {
viewer {
userWithAccount(accountId: $accountId) {
name
}
}
}
`;
class TestComponent extends React.Component{
constructor(props){
super(props);
this.state = {
accountId:14,
textboxValue: 14
}
}
onChange (event){
this.setState({textboxValue:event.target.value})
}
render () {
return (
<div>
<input type="text" onChange={this.onChange.bind(this)}/>
<QueryRenderer
environment={environment}
query={query}
variables={{
accountId: this.state.accountId,
}}
render={({ error, props }) => {
if (error) {
return (
<center>Error</center>
);
} else if (props) {
const { userWithAccount } = props.viewer;
console.log(userWithAccount)
return (
<ul>
{
userWithAccount.map(({name}) => (<li>{name}</li>))
}
</ul>
);
}
return (
<div>Loading</div>
);
}}
/>
</div>
);
}
}
Okay so my last answer didn't work as intended, so I thought I would create an entirely new example to demonstrate what I am talking about. Simply, the goal here is to have a child component within a parent component that only re-renders when it receives NEW props. Note, I have made use of the component lifecycle method shouldComponentUpdate() to prevent the Child component from re-rendering unless there is a change to the prop. Hope this helps with your problem.
class Child extends React.Component {
shouldComponentUpdate(nextProps) {
if (nextProps.id === this.props.id) {
return false
} else {
return true
}
}
componentDidUpdate() {
console.log("Child component updated")
}
render() {
return (
<div>
{`Current child ID prop: ${this.props.id}`}
</div>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
id: 14,
text: 15
}
}
onChange = (event) => {
this.setState({ text: event.target.value })
}
onClick = () => {
this.setState({ id: this.state.text })
}
render() {
return (
<div>
<input type='text' onChange={this.onChange} />
<button onClick={this.onClick}>Change ID</button>
<Child id={this.state.id} />
</div>
)
}
}
function App() {
return (
<div className="App">
<Parent />
</div>
);
}

How to move an index of a clicked item to another component that is not a parent?

Expecting effect: click <li> --> take index --> send this index to component Watch.
When I click <li>, I grab the index and move it to theWatch component. However, when I click the second li it returns the index of the one I clicked for the first time. I think this is because it updates this index via componentDidMount. How can I reference this index after componentDidMount?
Todo
class Todo extends Component {
render () {
return (
<div className = "itemTodos" onClick={()=> this.props.selectTodo(this.props.index)}>
</div>
)
}
}
export default Todo;
App
class App extends Component {
constructor(){
super();
this.state {
selectedTodoIndex: index
}
}
selectTodo = (index) => {
this.setState({
selectedTodoIndex: index
})
}
render () {
return (
<div>
<ul>
{
this.state.todos
.map((todo, index) =>
<Todo
key={index}
index={index}
todo={todo}
selectTodo ={this.selectTodo}
/>
)
}
</ul>
<Watch
selectedTodoIndex = {selectedTodoIndex}
/>
</div>
)
}
}
export default App;
Watch
class Watch extends Component {
constructor(){
super();
this.state = {
selectIndex: null
}
}
componentDidMount() {
this.setState({
selectIndex: this.props.selectedTodo
});
}
render () {
return (
<div>
</div>
)
}
}
First of all you you use selectedTodoIndex in
<Watch
selectedTodoIndex = {selectedTodoIndex}
/>
but it not specified in your render code. Add
const {selectedTodoIndex} = this.state;
in render function.
Second, use componentDidUpdate in Watch for update inner state on props update:
class Watch extends Component {
constructor(){
super();
this.state = {
selectIndex: null
}
}
componentDidMount() {
this.setState({
selectIndex: this.props.selectedTodo
});
}
componentDidUpdate (prevProps) {
if (prevProps.selectedTodo !== this.props.selectedTodo)
this.setState({
selectIndex: this.props.selectedTodo
});
}
render () {
return (
<div>
</div>
)
}
}
If i am not wrong your Todo component is in watch??. So Watch component should be like this :
render () {
return (
<div>
<Todo index={this.state.selectedIndex} selectedTodo={this.props.selectedTodoIndex}/>
</div>
)
}
Here i made codesandbox of this code . Feel free to checkout and let me know if you any doubt. Code link : https://codesandbox.io/s/frosty-chaplygin-ws1zz
There are lot of improvements to be made. But I believe what you are looking for is getDerivedStateFromProps lifeCycle method in Watch Component. So the code will be:
getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.selectedTodoIndex !== prevState.selectedTodoIndex) {
return { selectIndex: nextProps.selectedTodoIndex }
}
}
This will check if the selected index has changed in App Component, if yes it will update the state in Watch Component.

RN - Change parents' screenProps

I'm working on a React Native menu with a StackNavigator. If the user press a ListItem an id should be passed to all other Tabs in this menu, so the data can get fetched from an API. I tried to use screenProps to pass the data. Unfortunately I wasn't able to reset the value, when pressing a ListItem.
export default class Index extends Component {
constructor(props){
super(props);
}
render() {
return (
<OrderScreen
screenProps={ { Number: 123 } }
/>
);
}
}
In the child components I can access the prop but not reassign it:
export default class ListThumbnailExample extends Component
{
constructor(props)
{
super(props);
const{screenProps} = this.props;
this.state = { epNummer: screenProps.Number };
}
render()
{
return (
<Content>
<List>
{
this.state.orders.map(data => (
<ListItem key = {data.Number}
onPress = {() =>
{
this.props.screenProps.Number = data.Number;
this.props.navigation.navigate('Orders')
}
}
<Text>{ data.name }</Text>
</ListItem >
))
}
</List>
</Content >
);
}
}
Thank you!
In React and React-native props are immutable by design :
https://reactjs.org/docs/components-and-props.html#props-are-read-only
In your case if you want to pass screen-specific data you may wanna try passing them in the params of the navigation.navigate() function like this :
this.props.navigation.navigate('Orders',data.Number)
you can then access them in "Orders" screen from : props.navigation.state.params
More information here : https://reactnavigation.org/docs/params.html

Categories