How to access a function from React Functional Component in a Normal Javascript File?
Greetings Javascript Developers. I'm stuck in a complex situation now where I need to access a function inside one of my functinal components outside in a normal js file.
Ok So here's what I'm doing: This is my Authorizer.js
functional Component.
import React, { createContext, useState, useEffect, useContext } from "react";
import SplashScreen from "react-native-splash-screen";
import { useStore } from "../config/Store";
import { useDatabase } from "../config/Persistence";
import { getSessionCredentials } from "../config/Persistence";
import NavigationDrawer from "./NavigationDrawer";
import AuthStacks from "./AuthStacks";
const AuthContext = createContext();
export const useAuthorization = () => useContext(AuthContext);
export function Authorizer() {
//TODO check whether user is already signed in or not.
const realm = useDatabase();
const { state, dispatch } = useStore();
const [isAuthorized, setAuthorization] = useState(false);
useEffect(() => {
VerifyCredentials();
}, []);
async function VerifyCredentials() {
//TODO Check from Async Storage?
var session = await getSessionCredentials();
console.log("saved session", session);
if (session) {
await DispatchShopData();
await setAuthorization(true);
} else {
await setAuthorization(false);
}
sleep(1000).then(() => {
SplashScreen.hide();
});
}
async function DispatchShopData() {
try {
let shop = await realm.objects("Shop");
await dispatch({ type: "UPDATE_SHOP_DETAILS", payload: shop[0] });
} catch (error) {
console.log("failed to retrieve shop object", error);
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
return (
<AuthContext.Provider value={{ setAuthorization }}>
{isAuthorized ? <NavigationDrawer /> : <AuthStacks />}
</AuthContext.Provider>
);
}
This component basically handles my Authentication Flow, whether to show the Navigation Drawer or the Login Screen. Now I have another simple javascript file ApiService.js
which does not have any components, only simple js functions.
import Axios from "axios";
import { getAuthToken } from "../config/Persistence";
import { LogoutUser } from "../config/Persistence";
import { Alert } from "react-native";
const BASE_URL = "#########################";
/** Defined my Api Endpoints Here */
let service = Axios.create({
baseURL: BASE_URL,
timeout: 10000,
});
service.interceptors.response.use((response) => {
console.log("[API] response intercepted data", response.data.message);
if (!response.data.status && response.data.tokenExpired) {
//Auth token has Expired. Show user Alert for Session Expired & redirect to login screen.
Alert.alert(
"Your Session has Expired!",
"Don't worry though. You just need to login again & you're set.",
[
{
text: "Continue",
style: "default",
onPress: () => {
LogoutUser()
.then((success) => {
if (success) {
//TODO Find a way to Access this function from Authorizer.js Component.
//setAuthorization(false);
}
})
.catch((error) => {
console.log("failed to logout after session expiry", error);
});
},
},
]
);
}
return response;
});
/** Defined my other api functions called inside my other components */
function TestSampleApi() {
try {
return new Promise(async function (resolve, reject) {
const response = await service.get("https://jsonplaceholder.typicode.com/users");
if (response.data != null) {
resolve(response.data);
} else {
reject(response.status);
}
});
} catch (error) {
console.log("request error", error.message);
}
}
export {
TestSampleApi,
/** Exporting other api functions as well */
};
In my ApiService.js
file, I've setup a response interceptors whose job is to catch the default auth token expired response and SignOut user immediately and take him to the Login Screen. Here's now where my issue comes.
In normal scenarios, where I need to access functions from one component inside another component, I can manage is using CreateContext()
and useContent()
hooks. However, how do I access the useState function setAuthorization
in my Authorizer.js components in my ApiService.js
file as a normal js function.
I only need to call setAuthorization(false)
from my response interceptor block to make the user return to the Login Screen. Problem is idk how to access that state setter function. So any help would be greatly appreciated.
See also questions close to this topic
-
Creating a linked list object using js
I want to make a linked list using
custom Object
that pushes a value, pop a value, display all its content, remove an item from a specific place, and insert at a specific place as long as the value is missing from the sequence otherwise through an exception. All of the properties should be defined using data descriptor, prevent them from being deleted, iterated, or being modified.I can do no more than this ... I'm new to js.
var linkedList = {}; /* linkedList.name = 'Ahmed'; [].push.call(linkedList, 'sad', "sd"); */ Object.defineProperty(linkedList, "name", { value: "mohamed", writable: false, configurable: false, enumerable: false }) linkedList.next = {'sd':'as'};
Any help? thanks in advance
-
Trying to trigger a CSS animation with a button press through Javascript
I'm trying to trigger a CSS animation with a button press by using Javascript. I've used other question and answers here, but to no avail. My code seems like it should work -- what am I missing? When I click the button, the background color of the div which I specify should change color over 2 seconds to light blue. I've tried changing the color of both my Body and my Test div, but nothing changes. My alert() triggers, which is confusing as it is in the same function as my colorChange.
<!DOCTYPE html> <html lang="en"> <head> <title><model-viewer> example</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script> function colorChange() { alert("The button works"); document.getElementByID('test').style.animation="changeColor"; } </script> <style> body { background-color: darkblue; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; -o-transition: all 2s ease; -ms-transition: all 2s ease; transition: all 2s ease; } .test { width: 500px; height: 500px; background-color: pink; } @keyframes changeColor { to { background-color: lightblue; } } </style> </head> <body id="body"> <div class="test"></div> <button id="button" onclick="colorChange()">test animation</button> </body> </html>
-
No output from (GET) Ajax Result From Php Array with json_encode
I have a GET form that gets a Php Array and json encodes it. The Issue I am having is the succes data is not displaying. I want the success to display data in a Alert or console but for some reason its not working. I have tried many options. Thanks for your help.
PS:I know the GET and all files work because when I got the script the Ajax reponse result would populate/append a Table sucessfully. I am modifing it.
Here is the php index file with the AJAX:
<!doctype html> <html> <head> <title>Return JSON response from AJAX using jQuery and PHP</title> <link href="style.css" type="text/css" rel="stylesheet"> <script src="jquery-3.1.1.min.js" type="text/javascript"></script> </head> <body> <script> $(document).ready(function(){ $.ajax({ url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(data){ var obj = jQuery.parseJSON(data); alert(obj.username); } }); }); </script> </body> </html>
Here is the php file that quries the database and encodes/array json:
<?php $return_arr = array(); $sql = "SELECT * FROM users ORDER BY NAME"; $result = $conn->query($sql); //Check database connection first if ($conn->query($sql) === FALSE) { echo 'database connection failed'; die(); } else { while($row = $result->fetch_array()) { $id = $row['id']; $username = $row['username']; $name = $row['name']; $email = $row['email']; $return_arr[] = array("id" => $id, "username" => $username, "name" => $name, "email" => $email); } // Encoding array in JSON format echo json_encode($return_arr); } ?>
echo json_encode array output from the php file looks like below (test content):
[{"id":"1","username":"jiten","name":"Jiten singh\t","email":"jiten9"},{"id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldee"},{"id":"3","username":"mayank","name":"Mayank","email":"mayank"},{"id":"9","username":"mohit","name":"Mohit","email":"mohit"},{"id":"13","username":"mukesh","name":"Mukesh","email":"mukesh"},{"id":"6","username":"nitin","name":"Nitin","email":"niti"},{"id":"12","username":"palash","name":"Palash","email":"palash"},{"id":"7","username":"rahul","name":"Rahul singh","email":"rahul"},{"id":"10","username":"rohit","name":"Rohit singh","email":"rohit"},{"id":"8","username":"shreya","name":"Shreya","email":"shreyam"},{"id":"11","username":"sonarika","name":"Sonarika","email":"sonarika"},{"id":"5","username":"vijay","name":"Vijay","email":"vijayec"},{"id":"14","username":"vishal","name":"Vishal Sahu\t","email":"visha"},{"id":"4","username":"yssyogesh","name":"Yogesh singh","email":"yoges"}]
when I make the success result (data) and alert(data), this is what I get,empty objects
-
Deployment problems with React-Express App
I'm trying to deploy a MERN app (built with create react app) to Heroku, but whenever I try to access the URL, it returns with a 404 error.
During development I structured my project so that it runs on two different servers: client side on local host:3000, which proxies requests to express (at localhost:5000).
I've run
npm run build
, set up static middleware, and tried to configure my api calls/routes correctly, but it still isn't working. Any suggestions as to why, and how I can fix it? Details as follows:Project Structure
+client | +-build +-static +-css +-js +-media +-node_modules +-public +-src | +-components +-App.js +-index.js //server +-models +-node-modules +-package-lock.json +-package.json +-server.js
Proxy (in package.json):
"proxy": "http://localhost:5000"
Server config:
const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listening on port ${port}`)); //Middleware if (process.env.NODE_ENV === 'production') { app.use(express.static(path.join(__dirname, '../client/build'))); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.urlencoded()) app.use(cors())
Here's how I;ve structured my APIs. Note: I've removed the 'localhost:5000' from the URL of my axios requests:
API call from React component:
useEffect(() => { axios.get('/api/all-reviews') .then(review => { setReviews(review.data) }) .catch(err => { console.log(err) }) },[])
Corresponding express route
app.get('/api/all-reviews', (req,res) => { Review.find() .then((result) => { res.send(result) }) .catch(err => { console.log(err) }) })
-
How with Material UI to align input fields and buttons in the correct way in a dialog
In my React app, I have to align correctly the items in a dialog of MUI.
As per the screenshot, I have an issue to align the input fields Date and time. They should be aligned in the center and the Date input should start aligned with the title text above and the Time input should align with the button on the far right Save and close.
The second main issue is the buttons, I need to position Cancel and Save and close on the right and on the same row but on the left side, the button Remove call.
I have an issue making these alignments.
The code of the dialog
const useStyles = makeStyles(theme => ({ root: { margin: 0, padding: theme.spacing(1), '& .MuiFilledInput-root': { borderRadius: 0, }, }, dialogTitle: { marginTop: theme.spacing(2), }, container: { margin: theme.spacing(1), width: '80%', }, textField: { marginLeft: theme.spacing(1), marginRight: theme.spacing(1), }, button: { marginRight: theme.spacing(1), height: 40, }, paper: { overflowY: 'unset', }, closeButton: { position: 'absolute', left: '93%', top: '3%', color: 'gray', }, buttonRight: { justifyContent: 'flex-end', }, })); <Dialog open={open} fullWidth maxWidth="md" classes={{ paper: classes.paper }} > <DialogTitle className={classes.dialogTitle}> <Typography variant="h1" gutterBottom> Schedule a call </Typography> <InfoCallMessage call={appointment} /> </DialogTitle> {!loading ? ( <> <DialogContent className={classes.root}> <Grid className={classes.container} container justify="flex-end" alignItems="center" spacing={1} > <Grid item xs={8}> <MuiPickersUtilsProvider utils={LuxonUtils}> <DatePicker className={classes.input} disableToolbar variant="inline" label="Date" format="cccc, LLLL dd" helperText="" value={date} margin="normal" onChange={newDate => { handleDateOnChange({ newDate }); }} inputVariant="filled" fullWidth minDate={new Date()} /> </MuiPickersUtilsProvider> </Grid> <Grid item xs={4}> <TextField key={time} id="time" label="Time" type="time" defaultValue={time} className={classes.textField} InputLabelProps={{ shrink: true, }} variant="filled" margin="normal" onChange={e => { const { value } = e.target; setTime(value); }} fullWidth /> </Grid> <ErrorDateTimeIsAfter /> </Grid> </DialogContent> <DialogActions className={classes.buttonRight}> <IconButton className={classes.closeButton} onClick={() => closeDialog()} > <CloseIcon /> </IconButton> <Grid justify="space-between" container spacing={1}> <Grid item> <Button color="secondary" variant="contained" onClick={() => closeDialog()} className={classes.button} > Remove call </Button> </Grid> <Grid item> <Button color="primary" variant="outlined" onClick={() => closeDialog()} className={classes.button} > Cancel </Button> </Grid> <Grid item> <Button color="primary" variant="contained" onClick={() => handelSave()} className={classes.button} disabled={!isAfter(parseISO(`${date}T${time}`), new Date())} > Save and Close </Button> </Grid> </Grid> </DialogActions> </> ) : ( <Loading /> )} </Dialog>
-
transition animation not working in tailwindcss/react
I am a newbie learning React & Tailwind. I have a
Navbar
component which I have written like following,const Navbar = () => { const [showModal, setShowModal] = useState(false); return ( <> <nav className="flex justify-between items-center h-16 bg-white text-black relative shadow-md font-quicksand"> <Link to='/' className='pl-8'>Project</Link> <div className="px-4 cursor-pointer md:hidden"> {/* <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path> </svg> */} <button type="button" className="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500" id="main-menu" aria-haspopup="true" onClick={() => setShowModal(true)} > <span className="sr-only">Open main menu</span> <svg className="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /> </svg> </button> </div> <div className="pr-8 md:block hidden"> <Link to='/' className='p-4 font-bold'>Home</Link> <Link to='/menu' className='p-4 font-bold'>Menu</Link> <Link to='/about' className='p-4 font-bold'>About</Link> <Link to='/contact' className='p-4 font-bold'>Contact</Link> <Link to='/login' className="p-4 font-bold text-indigo-600 hover:text-indigo-500" role="menuitem">Log in</Link> <Link to='/register' className="p-4 font-bold text-indigo-600 hover:text-indigo-500" role="menuitem">Register</Link> </div> </nav> {showModal ? ( <div className="absolute top-0 inset-x-0 p-2 transition duration-500 ease-in-out transform origin-top-right md:hidden"> <div className="rounded-lg shadow-md bg-white ring-1 ring-black ring-opacity-5 overflow-hidden"> <div className="px-5 pt-4 flex items-center justify-between"> <div className="-mr-2"> <button type="button" className="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500" onClick={() => setShowModal(false)} > <span className="sr-only">Close main menu</span> <svg className="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> </div> <div role="menu" aria-orientation="vertical" aria-labelledby="main-menu"> <div className="px-2 pt-2 pb-3 space-y-1" role="none"> <Link to='/' className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-50" role="menuitem">Home</Link> <Link to='/menu' className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-50" role="menuitem">Menu</Link> <Link to='/about' className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-50" role="menuitem">About</Link> <Link to='/contact' className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-50" role="menuitem">Contact</Link> </div> <div role="none"> <Link to='/login' className="block w-full px-5 py-3 text-center font-medium text-indigo-600 bg-gray-50 hover:bg-gray-100" role="menuitem"> Log in </Link> </div> <div role="none"> <Link to='/register' className="block w-full px-5 py-3 text-center font-medium text-indigo-600 bg-gray-50 hover:bg-gray-100" role="menuitem"> Register </Link> </div> </div> </div> </div> ) : null} </> ) }
As you can see that when the screen got smaller the hamburger menu button will appear and when I click on that button it opens a modal with all the header components (The modal code copied from tailwind official components Hero components).
The problem is when that modal appears tailwind transition animation suppose to happen but it is not working. What am i doing wrong here?? Do i have to use the react hook
useEffect
somehow to make this work??Any kind of answer would be appreciated.
-
React Native How To Convert Route to Navigation State
I am trying to implement
react navigation v5
's deep linking system to myreact native
app. So far its working but I am started get confused. So my aim is makeinitial screen
to get params while navigating to specified screen. I can explain it better with code:const config = { screens: { HomeStack: { screens: { Home: { screens: { SearchStack: { initialRouteName: 'Search', screens: { PostDetailStack: { initialRouteName: 'PostDetail', screens: { PostDetail: 'post-detail/:postId', CommentDetail: 'post-detail/:postId/:comment/:commentId' } } } } } } } }, AuthStack: { screens: { ChangePassword: 'reset/:uid/:token' } } } }
So while navigating to
CommentDetail
screen I also want to pass params toPostDetail
screen. Inreact navigation
docs it says I need to usegetStateFromPath(path, config)
to copy params but I don't know how to use that. I tried to convert this route to state but I got confused and I also don't get when we useindex
in navigation state and when we don't. So how can I convert this to proper navigation state thatinitial screen
also gets the params? -
Only one default export per module allowed error on React Native with Navbar
I'm trying to make a Bottom NavBar with React Native with icons, but I have this error coming up Only one default export allowed per module. The issue comes from the last line export default createAppContainer(TabNavigator);
I tried to do it this way export default createAppContainer(TabNavigator)(Home) and remove the export default to my Home.js component but it's not working either.
Does anyone know what I'm doing wrong. All help will be welcome!
import React, {Component} from 'react' import {Text, View, StyleSheet } from 'react-native'; import {createBottomTabNavigator, createAppContainer } from 'react-navigation'; import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs'; import {Icon} from 'react-native-elements'; import Profile from "./Profile"; import Appointment from "./Appointment"; const styles = StyleSheet.create({ homeText: { fontSize: 40, }, homeCont: { flex: 1, justifyContent: "center", alignItems: "center" } }) export default class Home extends Component { render() { return( <View style={styles.homeCont}> <Text style={styles.homeText}>HOME SCREEN</Text> </View> ) } } const TabNavigator= createMaterialBottomTabNavigator({ Home: {screen:Home, navigationOptions: { tabBarLabel: 'Home', activeColor: '#ff0000', inactiveColor: '#000000', barStyle: {backgroundColor: '#67baf6'}, tabBarIcon:() => ( <View> <Icon name={'home'} size={25} style={{color:'#ff000'}} /> </View> ) } }, Appointment: {screen:Appointment, navigationOptions: { tabBarLabel: 'Appointment', activeColor: '#ff0000', inactiveColor: '#000000', barStyle: {backgroundColor: '#67baf6'}, tabBarIcon:() => ( <View> <Icon name={'calendar'} size={25} style={{color:'#ff000'}} /> </View> ) } }, Profile: {screen:Profile, navigationOptions: { tabBarLabel: 'Profile', activeColor: '#ff0000', inactiveColor: '#000000', barStyle: {backgroundColor: '#67baf6'}, tabBarIcon:() => ( <View> <Icon name={'person'} size={25} style={{color:'#ff000'}} /> </View> ) } } }); export default createAppContainer(TabNavigator);
-
Firebase Crashlytics Logs Fatal Exception: RCTFatalException: Unhandled JS Exception: TypeError: null is not an object (evaluating 'n.user_id')
Firebase crashlytics logs below error. How can i fix it. Thank you.
Fatal Exception: RCTFatalException: Unhandled JS Exception: TypeError: null is not an object (evaluating 'n.user_id') Unhandled JS Exception: TypeError: null is not an object (evaluating 'n.user_id'), stack: @1137:6471 touchableHandlePress@221:2200 touchableHandlePress@: _performSideEffectsForTransition@211:9639 _performSideEffectsForTransition@: _receiveSignal@211:8375 _receiveSignal@: touchableHandleResponderRelease@211:5663 touchableHandleResponderRelease@: b@99:1197 k@99:1340 C@99:1394 N@99:1692 A@99:2482 forEach@: z@99:2282 @99:13914 _e@99:88659 Ne@99:13582 Ue@99:13755 receiveTouches@99:14547 value@30:3685 @30:841 value@30:2939 value@30:813 value@:
-
change the value of useState with setInterval
I have a simple component with
useState
that increase a counter in each click -function Counter() { let [counter, setCounter] = useState(0); const incCounter = () => { setCounter(counter + 1); }; return ( <div className="App"> <h1>{counter}</h1> <button onClick={incCounter}>Inc</button> </div> ); }
and now I want to call the increase function each 1 second , so I added this piece of code into the component function -
useEffect(() => { setInterval(() => { incCounter(); }, 1000); }, []);
but I don't see the counter increased in the component.
How should I write it correctly and see the counter increased in each 1 second as expected ?
-
React hooks - send updated value from child to parent component when using onChange and prop of child toghether
I've two components - Parent and Child using
react hooks
.Here,
collected
is a state variable of parent component. And it's being passed toTenderInput
component.const handleBlur = (val) => { console.log('::: handleBlur :::'); console.log(val); setCollected(Number(val).toFixed(2)); } <TenderedInput default={collected} focus={focusInput} // onChange={handleBlur} />
In
TenderInput
const TenderedInput = (props) => { const [tendered, updateTendered] = useState(props.default); const handleChange = (event) => { const val = convertToCurrency(event.target.value); updateTendered(val); // props.onChange(event.target.value); this line causes an issue when I try to update state of parent with this call } return ( <div className="collected__amount"> <input type="text" className="form__input" value={tendered} onChange={event => handleChange(event)} onFocus={event => event.currentTarget.select()} autoFocus={props.focus} tabIndex="2" /> </div> ) }
TenderInput
'stextbox
and it'sonChange
event is working fine and updatingtendered
state ofTenderInput
component. But at the same I need to update parent's state. Now,collected
is in parent and if I addprops.onChange(event.target.value)
,collected
is getting updated every time we enter something in textbox and re-renders the component and doesn't allow to enter the correct value.I even tried to add
props.onChange(event.target.value)
inonBlur
onTenderInput
's textbox but then I need to click on a button twice to make it work.**How do I handle updating child component's state and at the same time update parent's state? **
-
Why setSlideCount not working as expected?
import React, {useState} from 'react'; function Slides({slides}) { const [slideCount, setSlideCount] = useState(0); const [slide, setSlide] = useState(slides[0]); const [restartDisable, setRestartDisable] = useState(true); const [previousDisable, setPreviousDisable] = useState(true); const [nextDisable, setNextDisable] = useState(false); const restartClick = () => { setRestartDisable(true); setPreviousDisable(true); setNextDisable(false); setSlide(slides[0]); setSlideCount(0); console.log("restartCLick ",slideCount); } const previousClick = () => { setSlideCount(prevCount => prevCount - 1); if (slideCount === 0) { setRestartDisable(true); setPreviousDisable(true); setNextDisable(false); setSlide(slides[0]); } else { setSlide(slides[slideCount]); } console.log("previousCLick ",slideCount); } const nextClick = () => { let newSlideCount = slideCount newSlideCount++ console.log(newSlideCount) setSlideCount(newSlideCount); if (slideCount === (slides.length - 1)) { setNextDisable(false); setSlideCount(prevCount => prevCount + 1); setSlide(slides[slideCount]); } else { setRestartDisable(false); setPreviousDisable(false); setSlide(slides[slideCount]); } console.log("nextCLick ",slideCount); } return ( <div> <div id="navigation" className="text-center"> <button data-testid="button-restart" className="small outlined" disabled={restartDisable} onClick={()=>restartClick()}>Restart</button> <button data-testid="button-prev" className="small" disabled={previousDisable} onClick={()=>previousClick()}>Prev</button> <button data-testid="button-next" className="small" disabled={nextDisable} onClick={()=>nextClick()}>Next</button> </div> <div id="slide" className="card text-center"> <h1 data-testid="title">{slide.title}</h1> <p data-testid="text">{slide.text}</p> </div> </div> ); } export default Slides;
The setSlideCount() is not setting the slideCount as expected, its incrementing late. Whenever I click nextSlide the increment is shown in the react developer tools but the value remains same of the slideCount. Same thing applies for previousClick button also. But for restart button it works properly in setting to 0 but for the next button clicks and previous button clicks the slideCount value is not updating as expected, please help in setting slideCount value.
-
How can I pass a param for a function inside my React Native Function Component?
I have a Picker component that is populated with data from a local realm database, the component has a function that receives the name of the database schema as a param. What I want to do is, instead of writing the name of the schema inside the function, to receive it as a prop or a param, so I can use the same component to show pickers with different information.
This is my code:
const PickerDB: React.FC<PickerProps> = (props) => { const [data, setData] = useState([]); async function loadData() { setData(await GetDataFromDB('source')); // this is what I want to modify } useEffect(() => { loadData(); }, []) let values = data.map((data) => { return ( <Picker.Item label={data.description} value={data.id} key={data.id} /> ) }) return ( <Picker selectedValue={props.selectedValue} style={{ height: 45, width: "70%" }} onValueChange={props.onValueChange} > {values} </Picker> );
I need to create my component using
React.FC<PickerProps>
because of other functions inside my app.I would like to use my component like this:
<PickerDB source={'schemaName'} />
-
Is there a way of using bootstrap studio to make react components (jsx)
In simple words, I want to design my components on Bootstrap Studio and then export them as a .js component that I can use. Currently, I know about (https://dev.to/thorstenhirsch/building-react-components-with-bootstrap-studio-a19) what's written here but I can't apply the export script mentioned in the link. I don't know what's the problem. Whenever I export using the export script an error is saved by the bootstrap studio in error file saying that it can't run the file. Please note if I'm giving the path right?
Export Script
#!/bin/sh TARGET="C:\Users\Dan Eyal\Desktop" [[ -z $1 ]] && echo "argument error: bss export directory required" && exit 1 [[ ! -d $1 ]] && echo "bss export directory does not exist" && exit 1 [[ ! -d ${TARGET} ]] && echo "target does not exist: ${TARGET}" && exit 1 # is rt installed? which rt >/dev/null 2>&1 [[ $? -ne 0 ]] && echo "rt (react-template compiler) is not installed" && exit 1 # main RC=0 for f in "$1"/*.html; do RTFILE="${f%.html}.rt" xmllint --html --xpath '/html/body/*' "$f" | tee ${RTFILE} sed -i 's|<script .*script>||g' "${RTFILE}" sed -i 's|%7B|{|g' "${RTFILE}" # fix due to xmllint/xpath bug 788398 sed -i 's|%7D|}|g' "${RTFILE}" # fix due to xmllint/xpath bug 788398 mv "${RTFILE}" "${TARGET}/" rt "${TARGET}/$(basename ${RTFILE})" RC=$(($RC+$?)) done exit $RC
-
React child components don't re-render when mapped from an array
I'm loading some react components on demand (among with other information) depending on user input.
The components to render are kept in an array and the render method usesarray.map
to include the components.The problem is, that if I trigger a
forceUpdate()
of the main app component, the mapped components won't update.Code example: https://codesandbox.io/s/react-components-map-from-array-ekfb7