how can i resolve error ? : node.scrollTo is not a function - javascript

When I run onPress in TodoItem component, I want scrollTo to be executed and scroll down as much as y: height value
but if i run onPress
node.scrollTo is not a function << this error occure
this is my code
(TodoList.js)
import React, {useContext, useState, useEffect, createRef} from 'react';
import {FlatList} from 'react-native';
import {
Dimensions,
NativeSyntheticEvent,
NativeScrollEvent,
ScrollView,
} from 'react-native';
const TodoList = ({replycomment}) => {
const height = Dimensions.get('window').height;
const [tabIndex, setTabIndex] = useState(0);
const flatListRef = React.useRef()
const refScrollView = createRef();
return (
<FlatList
ref={refScrollView}
style={{height}}
contentOffset={{x: 0, y: height}}
renderItem={({item}) => (
<TodoItem
onPress={() => {
const node = refScrollView.current;
if (node) {
node.scrollTo({x:0, y: height, animated: true});
}
}}
/>
)}
/>
(TodoItem.js)
import React, { useCallback, useState } from 'react';
import {FlatList} from 'react-native';
const TodoItem = ({onPress}) => {
return (
<MainContainer onPress={onPress}>
<Label>hi</Label>
</MainContainer>
i'm not sure why this error happend. how can i fix my code?? i want to use FlatList

From the Github source code of FlatList, I can only see 4 methods which help with scroll functionality :-
scrollToEnd(params?: ?{animated?: ?boolean, ...})
scrollToIndex(params: {
animated?: ?boolean,
index: number,
viewOffset?: number,
viewPosition?: number,
...
})
scrollToItem(params: {
animated?: ?boolean,
item: ItemT,
viewPosition?: number,
...
})
scrollToOffset(params: {animated?: ?boolean, offset: number, ...})
I think you need to make use of either of the above (since FlatList doesn't implement it's own scrollTo). I can see scrollTo usage inside VirtualizedList which is internally returned by FlatList.
Link to the source code - https://github.com/facebook/react-native/blob/master/Libraries/Lists/FlatList.js

Can you try using something like this :
node.scrollIntoView({ behavior: 'smooth', block: 'start' })

Related

React Native Render Html after get fetch request

I'm using the react-native-render-html npm package with expo. I'm trying to fetch some data from a website in useEffect and use the package to display the contents, however I keep getting the error of No source prop was provided. Nothing will be rendered.
I think the RenderHTML prop is being rendered before the request has been fulfilled:
import React, { useEffect, useState } from 'react'
import { ActivityIndicator, StyleSheet, Text, useWindowDimensions, View } from 'react-native';
import RenderHTML from 'react-native-render-html';
const EventsScreen = () => {
const [eventsHTML, setEventsHTML] = useState(null);
const {width} = useWindowDimensions();
useEffect(()=>{
fetch('https://www.google.com')
.then(response => response.text())
.then(response => {setEventsHTML(response);console.log("render");});
}, [eventsHTML]);
return (
<View>
{!eventsHTML? <ActivityIndicator/> : <RenderHTML contentWidth={width} source={eventsHTML}/>}
</View>
// <Text>The data has {eventsHTML? 'loaded' : 'not loaded'}</Text>
// <RenderHTML contentWidth={width} source={source}>Hello world</RenderHTML>
)
}
export default EventsScreen;
H
for rendering html first set html object like this:
const source = {
html: eventsHTML,
};
then pass this source object as props to RenderHTML component like this:
<RenderHTML contentWidth={width} source={source}/>

React useContext Returning Undefined

struggling to with react contexts being used with functional components. I feel like I'm doing everything right here, so any help would be much appreciated.
First I define a context (HeaderHoverContext.js)
import React, { createContext, useState } from "react";
export const HeaderHoverContext = createContext();
export function HeaderHoverProvider(props) {
const [currentHover, setHover] = useState(false);
const toggleHover = (e) => {
setHover(true);
}
return (
<HeaderHoverContext.Provider value={{currentHover, toggleHover}}>
{props.children}
</HeaderHoverContext.Provider>
);
}
I wrap the provider within my header (Header.js)
import React, { Component, useContext } from 'react'
import './header.css'
import Headerbutton from './Headerbutton';
import Hoverviewcontainer from './Hoverviewcontainer'
import {HeaderHoverProvider} from './contexts/HeaderHoverContext'
export default function Header() {
return (
<div className='header'>
<div className='header-right'>
<HeaderHoverProvider>
<Headerbutton text="Misc1" id="misc1" />
<Headerbutton text="Misc2" id="misc2" />
<Hoverviewcontainer id="misc3"/>
<Hoverviewcontainer id="misc4"/>
</HeaderHoverProvider>
</div>
</div>
);
}
Any then lastly, I try to retrieve the context using the useContext hook, but sadly its undefined.
import React, { useContext } from 'react'
import { HeaderHoverContext } from "./contexts/HeaderHoverContext";
export default function Hoverviewcontainer(props) {
const { isHover, setHover } = useContext(HeaderHoverContext);
// Returns undefined
console.log(`Current hover value is ${isHover}`)
return (
<div className={props.isHover ? 'hidden' : 'nothidden'} onMouseEnter={setHover}>
<div className="caret" id={props.id}/>
</div>
)
}
Any ideas what I might be missing here?
The fields in your context aren't called isHover and setHover, they are called currentHover and toggleHover, so either use them in the destructor or destruct manually:
const context = useContext(HeaderHoverContext);
const isHover = context.currentHover;
const setHover = context.toggleHover;
By the way, your toggle hover has a bug, never sets it to false. Try this instead:
const toggleHover = () => setHover(current => !current);

React Native state not resetting properly on navigating between screens

I am trying to implement the following case with two screens:
Adding players screen
Game screen: Challenges are read from JSON file and filled in with random variables during runtime. Example: in "p(1) drinks sips(2,4)" p(1) will be replaced with a random choice of a list of players, and sips will be replaced by either 2, 3 or 4 sips.
I am using stack navigation, passing the result of adding players in the player screen to the challenge screen. It works perfectly fine when I first start the game, but when I pop screen 2, and go back to screen 2, the challenges appear in random order (as expected), but they are already filled in.
The initialstate reads the non-filled in challenges from a JSON file, so why are the challenges already filled in when I rerender screen 2.
Gamescreen:
import React, { useState } from 'react';
import { StyleSheet, View, Text, TouchableWithoutFeedback, Alert } from 'react-native';
import ChallengeComponent from '../components/gameScreenComponents/challengeComponent'
import { shuffle } from '../helpers/shuffle'
import { fillInSips, fillInChars, fillInNumbers, fillInPlayers, fillInChoice} from '../helpers/challengeRegex'
const GameScreen = ({ route, navigation }) => {
const playersNeeded = (challenge) => {
return 0
}
const popChallengeHandler = () => {
if (challenges.length > 1) {
let newChallenges = [...challenges];
newChallenges.shift()
processedChallenges = playChallenge(newChallenges)
setChallenges(processedChallenges)
}
else {
setChallenges([])
}
}
const playChallenge = (currentChallenges) => {
currentChallenges[0] = fillInChallenge(currentChallenges[0]);
currentChallenges[0]['nextRounds'].forEach(round => currentChallenges.splice(round[0],0,{
initialRound: round[1],
nextRounds: []
}))
return currentChallenges
}
const fillInChallenge = (challenge) => {
return fillInChoice(players)
}
const endGameHandler = () => {
Alert.alert("Ending game")
}
const players = route.params;
const [challenges, setChallenges] = useState(() => {
const initialState = playChallenge(shuffle(require('../data/challenges.json').deck.filter(challenge => players.length >= playersNeeded(challenge))));
return initialState;
});
if (challenges.length > 0)
return (<ChallengeComponent pressHandler={popChallengeHandler} text={challenges[0]['initialRound']} navigation={navigation}/>)
else
return (<ChallengeComponent pressHandler={endGameHandler} text="Het spel is afgelopen" navigation={navigation}/>)
}
export default GameScreen;
Navigator:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import AddPlayerScreen from './screens/addPlayers';
import GameScreen from './screens/game';
console.disableYellowBox = true;
const RootStack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<RootStack.Navigator screenOptions={{headerShown: true}}>
<RootStack.Screen name="AddPlayers" component={AddPlayerScreen} />
<RootStack.Screen name="Game" component={GameScreen} />
</RootStack.Navigator>
</NavigationContainer>
);
};
export default App;
You can use this event listeners to doing some updates or else
navigation.addListener('blur', () => {console.log('focused Out')});
navigation.addListener('focus', () => {console.log('focused')});

componentDidMount or componentWillMount not working in React-Native?

Can anyone tell me what I am doing wrong here. I am trying to fetch cities using API but componentDidMount nor componentWillMount is working.
I have tested my getWeather function using button, the function is working but when I try to call the it using componentDidMount or componentWillMount it is not working...
My code below:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Header from './Header';
import { TextInput, Card, Button, Title } from 'react-native-paper';
import { useState } from 'react';
import { FlatList } from 'react-native-gesture-handler';
export default function Home() {
const [info, setInfo] = useState([{
city_name: "loading !!",
temp: "loading",
humidity: "loading",
desc: "loading",
icon: "loading"
}]);
getWeather = () => {
console.log("Hello Weather");
fetch("https://api.openweathermap.org/data/2.5/find?q=London&units=metric&appid={MY_API_KEY}")
.then(res => res.json())
.then(data => {
console.log(data);
/*setInfo([{
city_name: data.name,
temp: data.main.temp,
humidity: data.main.humidity,
desc: data.weather[0].description,
icon: data.weather[0].icon}]);
*/
})
}
componentWillMount = () => {
console.log("Hello Will");
this.getWeather();
}
componentDidMount = () => {
console.log("Hello Did");
this.getWeather();
}
return (
<View style={styles.container}>
<Header title="Current Weather"/>
<Card style = {{margin: 20}}>
<View>
<Title>{info.city_name}</Title>
<Title>{info.desc}</Title>
</View>
</Card>
<Button onPress={() => this.getWeather()} style={{margin: 40, padding: 20}}>Testing</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
componentDidMount and componentWillMount only work in class based React components; what you have here is a functional component. You can use the useEffect hook to accomplish the same.
useEffect(() => {
getWeather();
}, []);
Note that this does not exist in functional components; you can just call the function directly after you have declared it.
If you haven't used useEffect before, you may have questions about the array as the second argument. If it is empty, it will run on mount and will run what you return from the first argument on unmount. If you want to run your effect again, add an dependencies into the array.
ComponentDidMount would only work in class components. Using the useEffect React hook would achieve the same effect without issues

UseReducer is called twice when dispatching data from useEffect hook within child component

I am making a todo/shopping list in ReactJS. Besides being able to add items manually to the list by input, the user should also be able to add items programmatically.
I am using createContext() and useReducer for managing the state().
When I add items programmatically by providing an array through the props and listen for changes in useEffect, the useEffect and dispatch fires twice despite that I only changed the props once.
However this is NOT happening when I provide the array of items through props the first time.
Consequently, after the first time, when dispatch fires twice the list get duplicates (also duplicate keys).
Is it happening due to some re-rendering process that I am not aware of? Any help is much appreciated as I am really stuck on this one.
Here is the code:
Context provider component containing the useEffect that triggers the dispatch method from useReducer when the props change:
import React, { createContext, useEffect, useReducer } from 'react';
import todosReducer from '../reducers/todos.reducer';
import { ADD_INGREDIENT_ARRAY } from '../constants/actions';
const defaultItems = [
{ id: '0', task: 'Item1', completed: false },
{ id: '1', task: 'Item2', completed: false },
{ id: '2', task: 'Item3', completed: false }
];
export const TodosContext = createContext();
export const DispatchContext = createContext();
export function TodosProvider(props) {
const [todos, dispatch] = useReducer(todosReducer, defaultItems)
useEffect(() => {
if (props.ingredientArray.length) {
dispatch({ type: ADD_INGREDIENT_ARRAY, task: props.ingredientArray });
}
}, [props.ingredientArray])
return (
<TodosContext.Provider value={todos}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</TodosContext.Provider>
);
}
My reducer function (ADD_INGREDIENT_ARRAY is the one that gets called from above code snippet) :
import uuidv4 from "uuid/dist/v4";
import { useReducer } from "react";
import {
ADD_TODO,
REMOVE_TODO,
TOGGLE_TODO,
EDIT_TODO,
ADD_INGREDIENT_ARRAY
} from '../constants/actions';
const reducer = (state, action) => {
switch (action.type) {
case ADD_TODO:
return [{ id: uuidv4(), task: action.task, completed: false }, ...state];
case REMOVE_TODO:
return state.filter(todo => todo.id !== action.id);
case TOGGLE_TODO:
return state.map(todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
);
case EDIT_TODO:
return state.map(todo =>
todo.id === action.id ? { ...todo, task: action.task } : todo
);
case ADD_INGREDIENT_ARRAY:
console.log('THE REDUCER WAS CALLED')
return [...action.task.map(ingr => ({ id: uuidv4(), task: ingr.name, completed: false }) ), ...state]
default:
return state;
}
};
export default reducer;
The list component that renders each item and uses the context from above code snippet:
import React, { useContext, useEffect, useState } from 'react';
import { TodosContext, DispatchContext } from '../contexts/todos.context';
import Todo from './Todo';
function TodoList() {
const todos = useContext(TodosContext);
return (
<ul style={{ paddingLeft: 10, width: "95%" }}>
{todos.map(todo => (
<Todo key={Math.random()} {...todo} />
))}
</ul>
);
}
export default TodoList;
And the app component containing the list which is wrapped in the context provider that passes the props:
import React, { useEffect, useReducer } from 'react';
import { TodosProvider } from '../contexts/todos.context';
import TodoForm from './TodoForm';
import TodoList from './TodoList';
function TodoApp({ ingredientArray }) {
return (
<TodosProvider ingredientArray={ingredientArray}>
<TodoForm/>
<TodoList/>
</TodosProvider>
);
}
export default TodoApp;
And the top level component that passes the props as well:
import React, { useEffect, useContext } from 'react';
import TodoApp from './TodoApp';
import useStyles from '../styles/AppStyles';
import Paper from '#material-ui/core/Paper';
function App({ ingredientArray }) {
const classes = useStyles();
return (
<Paper className={classes.paper} elevation={3}>
<div className={classes.App}>
<header className={classes.header}>
<h1>
Shoppinglist
</h1>
</header>
<TodoApp ingredientArray={ingredientArray} />
</div>
</Paper>
);
}
export default App;
The parent component where ingredientArray is made. It takes the last recipe in the state.recipes array and passes it as props to the shoppingList:
...
const handleSetNewRecipe = (recipe) => {
recipe.date = state.date;
setState({ ...state, recipes: [...state.recipes, recipe] })
}
...
{recipesOpen ? <RecipeDialog
visible={recipesOpen}
setVisible={setRecipesOpen}
chosenRecipe={handleSetNewRecipe}
/> : null}
...
<Grid item className={classes.textAreaGrid}>
<ShoppingList ingredientArray={state.recipes.length ? state.recipes.reverse()[0].ingredients : []}/>
</Grid>
....
What am I doing wrong?
Glad we got this sorted. As per the comments on the main post, mutating React state directly instead of updating it via a setter function can cause the actual value of the state to become out of sync with dependent components and effects further down the tree.
I still can't completely reason why it would be causing your specific issue in this case, but regardless, removing the mutative call to reverse and replacing it with this simple index calculation appears to have solved the issue:
state.recipies[state.recipies.length-1].ingredients

Categories