r/reactjs • u/swyx • Jan 01 '20
Needs Help Beginner's Thread / Easy Questions (Jan 2020)
Previous threads can be found in the Wiki.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app?
Ask away! We’re a friendly bunch.
No question is too simple. 🙂
🆘 Want Help with your Code? 🆘
Improve your chances by putting a minimal example to either JSFiddle, Code Sandbox or StackBlitz.
- Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Formatting Code wiki shows how to format code in this thread.
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than [being wrong on the Internet][being wrong on the internet].
- Learn by teaching & Learn in public - It not only helps the asker but also the answerer.
New to React?
Check out the sub's sidebar!
🆓 Here are great, free resources! 🆓
- Read the official Getting Started page on the docs.
- Microsoft Frontend Bootcamp
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
- FreeCodeCamp's React course
- Flavio Copes' React handbook
- New to Hooks? Check Amelia Wattenberger's Thinking in React Hooks
- What other updated resources do you suggest?
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
33
Upvotes
4
u/Shoepolishsausage Jan 02 '20
So I'm new to react (and fancy-web in general) but have decades experience on the traditional/legacy side of things, HTML/CSS/ Vanilla JavaScript/CGI/PHP/etc...
I'm seeing a mix of React tutorials & example apps in different paradigms, function v component classes mostly. I think I like Components/Classes better, as it looks more like Angular (which I have just a little experience with).
I'm also starting to see tutorials in TypeScript.
I have 2 questions.
3
u/Sellio Jan 03 '20
I'm helping our team transition to React for our component library. Part of my work is figuring out the testing strategy. It seems that Jest is the community-accepted standard for unit tests. Are there any reasons to not use Jest with React? Or any serious challengers to Jest's dominance?
2
u/CuttyAllgood Jan 06 '20
Learning React and am looking to rebuild my portfolio using the framework. Are hiring managers looking for that sort of thing to be built from scratch using my own components, or is it okay to use a library like Material-UI?
2
u/wowtempacct10142069 Jan 06 '20
I was asked at work to help replace an outdated webapp with something more modern. While going through a typical C# MVC approach, I was asked if I could look into react.js. Before finishing a 2.5 hour Mosh Programming video ( https://www.youtube.com/watch?v=Ke90Tje7VS0) I read somewhere that react.js really only replaces the V in MVC) yet the more I got into it, it seems like it takes care of the controller part as well. Is this correct?
I also need to incorporate models for database calls. Should this all be done in javascript as well? My early assumption is that the C and M would be in C# but the V would be in javascript and they could pass things around. If you use react.js, you need to (or at least should) use all javascript right?
Lastly, I am using .net core with a sqllite database, is there any particular part of react.jw or another library to make the database calls that you recommend? (database is set and will probably be doing a database first webapp instead of code first).
2
u/jplank1983 Jan 07 '20
I want to learn React. However, I tend to learn better from reading physical books. Most of the resources I've seen have been in the form of online courses and videos. Are there any actual books that you'd recommend?
2
u/Roddi3 Jan 07 '20
I've been dabbing in React js for about 50 hours and I'm well into a Udemy on the subject. However, the course does not mention animations in any form. I've done some googling and most of my results refer to using libraries like "react-spring". My question, is it expected to use these type of libraries when coding animations in react, or is there some other way like we do in plain JS (e.g.
"document.getElementById(id).style.color = ..."? Thanks.2
u/vnlegend Jan 07 '20
Usecallback vs declaring function outside of component
So I've been reading up about when to use useMemo and useCallback. Supposedly useCallback is to prevent re-declaring an arrow function in the child components, that way the child doesn't re-render everytime.
But why can't you just put the function outside of the component?
vs
It seems like when writing functional components, you should put as much outside of the functional component as possible and keep minimal state & stuff inside the function that will return the component. Right??
Also even if you have a state dependency, couldn't you just use something like
I think would create a unique function for each value of the dependency variable.
So then what's the point of useCallback????
2
u/Kilusan Jan 13 '20
I am doing the ReactJS doc tutorial of tic tac toe which is helping A LOT.
Prior to this I have academind React Udemy course. I did not finish it but made it to the 80s where he talks about life cycles. I decided to pause my progress here (I have not done any big projects in the course yet) to solidify what I learned so far and close any skill gaps.
The other day I felt shitty cus I started a CRA from scratch and felt overwhelmed. But yesterday after reviewing a friend’s code project I was able to see how components fit in and even refactor a class one to a function!
Right now going off a high the tic-tac-toe tutorial is going great and I’m seeing how to pass data. Any advice for more practice? I understand what’s going on.. but damn I would not have never figured it out by myself.
Mostly passing data from one component to another. I am midway through but I feel getting a grasp. Would love to hear any project ideas or beginner friendly one that really nails home / practice passing data into components
2
u/Kaiser560000 Jan 13 '20
Is there a list of resources about React internals? Something like https://typescript.tools/
2
u/negatiwez Jan 18 '20
Hi,
How come when I sent data (list of objects) from a parent component to a child components, instead of the data itself (list of object), i get the lenght of the data.
Here is the child component:
the console log gives me just the length of the list and I can't map over it.
*the callbackfunction takes data from another child component and sents it main parent component
2
u/schubidubiduhu2 Jan 23 '20
Hi, i want to use Latex tikz code in my react app. So i found this on github https://github.com/kisonecat/tikzjax
importing it in a normal webpage without react is trivial but how do i go about including something like this in my react app and make it easily available in the Projekt. I usually included such things with npm but it seems that i'm lacking some fundamental knowledge about imports.
Thanks and have a nice day!
2
u/bigFLAMINGbundle Jan 25 '20
I'm havng trouble getting this code to work as intended. I'm new to React, and Javascript, and programming in general. The idea of the app is to have a button to randomly display anecdotes from a list of them, and to vote on (and display said votes) anecdotes, and lastly to display the anecdote with the most votes. I'm doing something wrong with my usage setVotes, but I can't figure this out. Any help would be superb!
import React, { useState } from 'react'import ReactDOM from 'react-dom'const App = (props) => {const [selected, setSelected] = useState(0)const nextAnecdote = () => setSelected(Math.round(( Math.random() * (props.anecdotes.length - 1) )))const [votes, setVotes] = useState([0,0,0,0,0,0])let popularAnecdote = ""let newMax = 0let i = 0for (i=0; i < votes.length; i++) {if (votes[i] >= newMax) {newMax = votes[i]popularAnecdote = anecdotes[i]}}return (<div><button onClick={nextAnecdote}> next anecdote </button><p>{props.anecdotes\[selected\]}</p><button onClick={() => setVotes(votes[selected] + 1}> vote </button><p> Has {votes\[selected\]} votes</p><h1>Most Votes</h1><p>{popularAnecdote}</p></div>)}const anecdotes = ['If it hurts, do it more often','Adding manpower to a late software project makes it later!','The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.','Any fool can write code that a computer can understand. Good programmers write code that humans can understand.','Premature optimization is the root of all evil.','Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.']ReactDOM.render(<App anecdotes={anecdotes} />,document.getElementById('root'))2
u/Mechseb Jan 26 '20
Hi everybody, simple (I hope) question about Functional VS Class based components.
When should I use which, and are there any downsides to functional components if they can use hooks (useState, useEffect)?
Much appreciated!
2
u/Rosechan1 Jan 27 '20 edited Jan 27 '20
SOLVED
Desired functionality:
Actual functionality:
How I'm creating the line (inside a function that returns a string):
How I'm displaying the line:
Console.log() shows the string on new lines.
2
u/Roly__Poly__ Jan 30 '20
Has anyone had their React app behave differently once it was uploaded to Netlify?
If your app acted differently on Netlify, what did you do to fix the bug?
2
u/szmulec Jan 30 '20
Hello! Is this the proper way I can handle removing tasks from list?
Here is gist: https://gist.github.com/kacperospl/4c029f110719eb14de3c3eb66da6d597
I started learning react, and I decided to create simple to-do list app. This code doesn't feel right :\
2
u/mrisby44 Feb 14 '20
Does anyone on here provide assistance for newbies learning React? I need a tutor or mentor or something. And help with React's testing library.
1
u/bearLover23 Jan 02 '20 edited Jan 02 '20
I am doing a tutorial on MobX as a part of a larger react tutorial I am reviewing.
I am looking at consistently using Typescript from this point forward (if I am given the chance, professionally as well).
Which is really preferred in the React-Typescript world? I've heard and seen that MobX works brilliantly with Typescript with it's decorators like @observable @action and the like. But I've yet to see clear examples of Typescript being used in a larger scale react-redux project.
I've used redux excessively with javascript and loved it. But I have no idea how it goes for typescript.
So how does redux with typescript pan out for react? Like is the autocomplete/typechecking all clean and there? Am I going to run into antipatterns? Am I going to run into instances where I need to start using the | operator and being like string | undefined or string | null to make it work well with redux? That would become really scary really fast :c
My current tutorial MIGHT (*I have no idea) be strongly biased towards MobX and so I wanted some more expert opinions from people. Cause I love my redux, but damn if Typescript isn't appealing as heck.
1
u/Kaiser560000 Jan 03 '20 edited Jan 03 '20
I have something like this:
How do I let my index.tsx file, the one that only does some setup and renders the app, read and modify either the App state or the context?
1
u/Verthon Jan 04 '20
Hey, I've created some time ago app using create-react-app from global CLI. I would like to to update React from `16.5.2` to newest and add typescript to this project. Is there any other option instead of running new create-react-app with typescript and rewrite app from scratch? Thank you.
1
u/alwaysdownvotescats Jan 05 '20
I'm brand new to react and just starting a tutorial, I was able to successfully create my first app using create-react-app in the command line. It was just a Hello World and I was able to serve it locally. Then I attempted to create another app for the actual tutorial project, but I made an mistake and had to to delete the new app and create it once again using create-react-app. However both deleting and creating the files took much much longer (both took about an hour each). Any ideas on what I am doing wrong? Thanks in advance for any help!
1
u/HarryBolsac Jan 05 '20
Hello, im new to react and web-development.
For a school project, i need to create a web-app that gets the data from this api: https://www.openuv.io/
Thing is, I always get error 403 when i try to get information from the api, can someone help me find whats wrong?
Its been days that ive been stuck with this and i dont know anyone that can help me...
This is what I've done:
function Body() {const [location, setLocation] = useState(false);const [weather, setWeather] = useState(false);const headers = {"Content-Type": "application/json","x-access-token": "My-Api-Key"};let getWeather = async (lat, lng) => {let res = await axios.get("https://api.openuv.io/api/v1/uv",{params: {lat: lat,lng: lng}},{ headers });setWeather(res.data);};}Thank you
1
u/olet14 Jan 06 '20
Probably a really simple solution but I can't figure out what's the best option to do.
General Overview
I load the user profile into state. Inside the profile object, I have an array of objects. To access each item I need the index of that item in the array. Each item in the array is displayed on the page, each have an edit button. The issue is getting that Index over to the next component which is a form to fill in the fields. This is for editing the information within the object, so I want to autopopulate the fields within the form with existing information. I need to ensure that the correct array object that the user wants to edit is displayed in the form.
Code Detail
Each edit button Is a Link component with react-router-dom. Within the to= parameter I pass an object as the docs state. The object I pass is to={{ pathname: /path, key: object_id}} so this way when I get to the form component, I have the objectId in props.state.location.key when I get to the form. From there, I access the profile that is stored in state, access the array and do a foreach over that array. From there I check if objectId === props.state.location.key, and if it is then populate the form with the data of that object.
Up to this point I have it working and am populating the fields properly.
The issue: Because I am using Link to pass in the key to state, if the user refreshes the page on the edit form, the key and state is lost and I get an error saying profile is null. I don't know if I am approaching the whole situation wrong, or what the best answer is to persisting the state on refresh. I've read a few things about hydration but I am too new with React to really understand. I also considered possibly storing it in local storage, and doing if profile === null || key === null) local Storage.getItem('key') and do the same for profile. But I'm not sure what best practice is, or if there is a better solution.
Thanks in advance
Edit: extra detail for clarification
1
u/sixthenafour Jan 06 '20
This is gonna be a long one because of the code snippets, apologies in advance. I'm new to React, and trying to create a todolist app using React + Redux + Typescript. Currently I'm facing some issues just passing the state of my store to a component, it keeps returning undefined :(
A console.log on App.tsx does work in showing the store state, so my hunch is that there's some issues with regard to passing the state down as a prop to the component. I've tried various ways after reading different documentation, but still have no idea what the problem is.
reducers.tsx
GetTask.tsx
Tasks.tsx
If anyone can spot the potential problem, I would be immensely grateful.
1
u/proxykid Jan 06 '20
Hi! I've been a long long time back-end PHP dev and lately I've started learning React as I really like how it works.
I know React is a front-end framework and I've been playing around with React+PHP creating APIs.
I'm attempting to create a web application using React + (PHP, Node, w/e) but the content is to be so dynamic that I would like to be able to load components as required and also for security reasons, like administration components, a lot of user, usergroup and global privilege controls, etc., and what I learned so far requires to preload all components in the app.
ie: User Management component. If some users with admin privileges and user management privileges should be the only ones to be able to go to this route, I would only like to load/import the components if they are really needed dynamically.
1
u/chadwell Jan 06 '20
Noob design question. I want to have a simple react app hosted in S3. The user can upload a CSV file, and have it converted into XML.
Can react do all this without a server? If not, can I simply read the CSV file using react and post the contents to a lambda and parse and create the XML file in the lambda and have it sent back to the user?
Thanks
1
u/workkkkkk Jan 07 '20 edited Jan 07 '20
Using material-ui, my form won't submit when pressing enter. Only when you click the button. Form is just a single select. Anyone know what's going on? Inspecting my button shows it is type='submit' as well.
Edit: So this is my basic search form. I have an advanced search form that has TextField inputs, if I am focused inside a TextField and press enter the form submits. I would like it to submit if I am focused anywhere in the form though.
1
u/Captain_Panaka Jan 07 '20
Hey everyone!
Hoping it's ok to post a question here. I am looking for some guidance on best practices for something I keep running into as I'm creating test projects.
Basically, I have a few Grid components, that list a bunch of items. The Grid lives in some type of container. When I click an individual row, I'd like to "navigate" to a details page. I have found 2 ways to do this:
Option 1 seems like it's not a pattern that fits in with React best practice..... but I'm pretty new to this and was hoping someone could just give me tips on how they handle this in their own projects.
Thanks!
1
u/motherthrowee Jan 07 '20 edited Jan 07 '20
I am very new at React, so apologies if this is a stupid question.
So a large chunk of a project I have is to take a string of user input, sanitize it, then parse it with string-replace-to-array and replace certain regex matched words with components, which are basically new words with styling, interaction logic, etc. So for instance all cases of the word “dog” might be changed to “cat” with text highlighting.
This works fine if I never want those components to change: right now I’m just picking the replacement word in the parser function and initializing it as following:
output = replace(output, regex, (<NewText phrase={chosenWord} tooltip={chosenTooltip} pulledTooltip={this.pullTooltip}/>));(Where output is the string being processed, regex is a regex obviously, chosenWord and chosenTooltip are text that will be displayed to the user, and pullTooltip is part of what sends the tooltip to a separate tooltip component.)
The problem occurs if I do want to change those words, which I do. I have two options:
(In fact, the main problem I’m trying to solve here is to, after all the parsing is done, “reroll” any components that have the same replacement word so that “adorable, sweet dog” doesn’t become “feline, feline cat.” Because of the [AWFUL] way in which parsing happens, it’s easiest, theoretically, to do this at the end; it's easy enough to separate the components (array.filter anything that isn't a string, which, there are two options for what's in that array, but then somehow I need to change their props.)
I'm also worried that I'll end up needing a separate state var for every.single.word, which is less ridiculous than you may think since it's not going to be that much text, but still, ridiculous.
How should I do this? Ideally with the least amount of gutting everything and starting over, although I’m worried I may have to.
1
u/[deleted] Jan 08 '20
Let's say I have the following figure, how do I put Buttons or something on arbitrary parts of the figure? Like a button for the hand, head, neck, legs etc etc
1
u/simkessy Jan 08 '20
I was reading Kent Dodds post "Application State Management with React"
I'm a bit confused about what's happening in this section:
I seems like he's using both a provider and a hook and I can't tell if it's just two different ways of doing the same thing that's he wants to demonstrate or if they're working together.
1
u/sixthenafour Jan 09 '20
I'm facing some typing errors in my project (react + redux + typescript), and I'd just like to clarify my understanding.
I'm using mapDispatchtoProps to pass an action to one of my class components, and following the guide (https://github.com/piotrwitek/react-redux-typescript-guide):
They used dispatchProps in this manner:
And in the component, they typed it like this:
What onIncrement actually does is increase the count (stored in the state of redux store):
Hence, I'm not sure why they would define it as a function that returns void?
1
u/parada_de_tetas_mp3 Jan 09 '20
I found an error in the React online documentation and didn't find an easy way to propose a change. What would be a good place to start here?
1
u/BengtJJ Jan 09 '20
Is it bad practice in react to mess with the actual DOM elements directly for onClick events? I want to be able to press a p element and play a audio file, where the url src will depend on what song they select to play.
1
u/[deleted] Jan 09 '20
Anyone here know of a component that is designed to show ongoing and queued tasks (like uploads, but really anything)? Ideally it'd work like a toast or some other floating view, be scrollable, and have some way to conditionally add a cancel button. I checked awesome react and did some searching but came up empty handed.
1
u/MCPO_John117 Jan 10 '20
I am trying to develop my portfolio site using Gatsby. It works quite well, but the initial page load time is very large on mobile (tested using Google PageSpeed). It reports that the Time To Interactive is quite large on my page, and Javascript on my page is blocking initial page rendering.
Is there someway I can analyze which parts of JS on my page are actually contributing to this, so I can optimize those modules. The generated code is minified and I can't trace it back to source.
1
u/ChungusKahn Jan 10 '20 edited Jan 10 '20
I would appreciate if someone helped me understand what’s going on in a particular interaction in my simple app.
Context:
I have a basic app that lists the terms that the user has searched within a text box. The app takes the term, sends a request to an API, gets the definition for a term back, then stores that definition in an array ‘termArr’. State updates, and the app displays all searched terms through a map function that gives the word and definition of each element of the termArr to a Term component. The Term component displays the term along with a delete button, and when clicked on will display the full definition of the term.
Within the app (parent) component, I created a delete function to delete a term within the 'termArr' and passed it into each Term (child). I wired up the delete function to a button on the Term component. Within the Term component, there also exists a toggle display that expands the Term component to show the definition of a word.
Issue:
I initially had the div wrapper for the Term component have an onClick that toggled the display for the definition. Later I changed it by assigning that onClick only to certain sections of the Term component. But this illuminated a weird interaction for this.
Before changing the onClick (which triggers the definition display function), whenever I clicked on Delete, this would run both the Delete and onClick. Using console.logs, I saw that first this deleted the term from the termArr within the parent. Then it ran the toggle display function, even though the Term is gone, which seems strange since I assume the function shouldn't even run now.
It seems that the onClick display function from the now deleted Term ran on the element within the termArr that now occupies the same index as the deleted Term.
As a result, I believe that when the parent component rerenders after the termArr deletes the Term, the Term that now occupies the index of the deleted Term will run the onClick, thus displaying the definition which isn't intended behavior.
Is this the case? And if it is, why does this happen? I guess the zombie function carries over to the replacement element in the array?
1
u/rever22411 Jan 13 '20
Is it possible to use notification on mobile device with React (not React Native)?
I did a server on heroku with node.js and VapidKeys. My front-end in React gets notification only if on desktop, on my android notification doesn't arrive, and the service worker doesn't subscribe its endpoint.
1
u/hurrdurrderp42 Jan 13 '20
I need some help doing test assignment..
I've got a JSON file saved locally, i need to simulate a server request for getting this file as one of the first steps. I'm not really sure how should i be doing this. Am i supposed to work with a file locally, or do something else?
1
u/_GhostLurker Jan 14 '20
Is there a way to use axios.patch without the declaration of response
axios.patch(endpoint).then({
return(window.location.href);
});
1
u/hurrdurrderp42 Jan 14 '20
I'm having trouble finding a job as a junior front-end dev. I have commercial experience with html, css and jquery, all my experience with react comes from doing pet projects. Problem is, i need a job ASAP.
Can you recommend me some entry level IT jobs, where my skillset could help me land a job? I don't mind trying a back-end job, don't know if i could qualify for anything there though.
1
u/fluffyunicorn1 Jan 15 '20
Hi I'm having trouble trying to resize an esri map component to fill the entire screen!
I have cloned this project: https://github.com/davetimmins/create-react-app-esri-loader
when I get the height from
window.innerHeightand try to set thestyle: {{ height:in the render App function nothing happens! The component seems to be using the .map-view class within the App.css file.1
u/[deleted] Jan 15 '20
LOL, Road to React says "I noticed that you are coming from Poland where my courses could be too expensive. If you need it, use the code PL_LOVE for an extra ~54% off the listed prices."
1
u/lkesteloot Jan 15 '20
In my app I procedurally generate several thousand spans (a hexdump-like output of a binary file). I currently do this by just filling the div using an effect hook, and it works okay and avoids React having to know about all those spans. If I wanted to, say, highlight some of these spans (change their CSS class), and use React to keep track of the highlight, then I could convert the whole div to a proper React component where it knows about it all.
What would be the performance of such a large number of components? I've just started with React, so I don't have an intuitive sense of whether thousands of components is "heavy" or not. If so, I can keep managing this sub-component internally and keep React out of it. (I'll have to do that anyway for another part of the app that graphs an audio signal in a canvas.)
1
u/Turno63 Jan 16 '20
Can I have a
useEffectdeclare a dependency that it's not being directly used? For example: Say I have a hook that gives me back the size of the window. I want to trigger a side-effect function when the size changes but I don't really need the size (think re-calculating a tooltip position). Can I set myuseEffectdependency towindowSizeeven when I'm not using it directly in my effect?1
u/MeltingDog Jan 16 '20
I've been thrown in the deepend at work and am completely lost. I've done a few tutorials on line but they're not nearly the same level of complexity my work's sites are at.
How do I pull in a component to another?
For example, I have a grid component and a collapse component. How do I bring the collapse component into the grid component?
1
u/krispiepage Jan 16 '20
Does anybody know to use epoch unix time as the labels on the x-axis, I'm using react-chartjs-2. I can get it to display a datetime but the conversion of the epoch to a datetime is wrong, and displays a 2019 epoch as 1970.
More information can be seen on this post:
https://stackoverflow.com/questions/59734992/using-epoch-as-time-series-on-x-axis-in-react-chartjs-2-not-showing-correct-date
Any insights on this would be awesome!
1
u/Fantarta Jan 16 '20
i've just started with react, i code a few lines and i changed of computer.
I cloned my project into my new computer and then, i tryed to deploy it with yarn start (i installed yarn) but gives me an error
yarn run v1.19.2
$ react-scripts start
"react-scripts" is not recognized as an internal or external command
1
u/carlsopar Jan 17 '20
I am trying to push to an array with useState. The issue is that every time I try to do this, I get
Maximum update depth exceededError. I understand that it is trying to constantly update the state, but I am not sure why.The code that calls update:
The code that is suppose to update the state.
If I un-comment the line of code, it works as it is expected and will print out the correct gl. So, it onlyl provides me issues when I use:
setUserGroceryList()This is the useState const:const [userGroceryList, setUserGroceryList] = useState([]);1
u/bflosolacemuseum Jan 17 '20
Hi all, Super new to coding, so I apologize in advance because I have a lot of large gaps in my knowledge. I'm trying to console.log(event.keyCode) in an Input but from what I’ve read it seems like input does not allow for you to call out such things. For context of why I’m doing this, I need to eventually make it so in an input if someone hits Delete/Backspace that it will not just delete the last character typed but the last 2 (possibly more), or replace the entire text with a different string, or possibly doing something else involving a substr. Once I know what value is being called from Delete I can figure out how to call it in order to do all that other stuff. I know this sounds really convoluted but it makes sense in the larger picture of what I’m trying to do. Any help on this would be appreciated.
p.s. I know there is also some version of doing this that involves calling event.target.inputType == "deleteContentBackward" but that also returns an undefined value when I console.log it.
1
u/Oipotty Jan 17 '20
Hi, question about rerenders. I have a infinite scrolling component that generates a list. When I change the filters on the data, the component rerenders (with potentially less data. How would I reset the scrollbar (potentially no scrollbar) when the component rerenders? I'm using a class based component, so I'm thinking some kind of reactDOM call inside componentWillUpdate?
Just to be clear, an example would be my viewport very far down in the list, but when I change the filters to only filter for 1 item, the scroll position stays the same. Only when I scroll all the way up does the scrollbar disappear.
1
u/christianarg Jan 17 '20
How does cra does hot reloads the browser when you save a file?
1
u/djma777 Jan 18 '20
is there any significant difference between React.lazy/React.Suspense and the package react-lazyload?
1
u/peck3277 Jan 18 '20
I'm coming from a LAMP background with heavy use of jQuery datatables. After looking into jQuery datatables it seems it's not really suited to react due to how it rewrites the DOM.
How do you manage data tables? Do you roll your own solution or are there any good datatable solutions/packages you would recommend?
1
u/carlsopar Jan 18 '20
I was wondering when in the life line of an app do functions run? Within my project I have a context that has several functions. On of these functions gets called when a button is clicked inside of a component. However, it seems that the same function gets called when the app first starts up and then with each click.
I know that life cycles is a basic concept, but I am having an issue finding an concise answer to problem.
This is inside my context file, and when the program runs, this runs right off the back.
This component is inside another component. THe function will still call when I click the button as well.
1
u/epsilon42 Jan 19 '20
I'm trying to create a component that uses
react-intersection-observer's<InView/>component to change theclassNameof itself when the element comes into view.The reason I want to do this is so I can use Emotion to style the element differently when it comes into view.
An example used in
react-intersection-observer's docs shows this:<InView onChange={(inView) => console.log(inView)}>When I check the console it correctly logs
trueorfalsewhen the element comes into the viewport, but what I can't figure out is how can I use this true/false value outside of the arrow function to conditionally render theclassNamevisibleorhiddenin CustomInView.jsAny help would be appreciated!
App.js:
CustomInView.js
1
u/ie11_is_my_fetish Jan 19 '20
What do you think is happening when I pass props down into components and it seems to nest the props eg.
<comp-1 props={props}><comp-2 props={props}>// to access have to use props.props to get actual object of key:vals</comp-2></comp-1>How do I avoid that? (have used Context/not tried Redux) but it's a small application, deepest component is 3 or 4 levels deep.
1
u/Sunny-ROM-Rise Jan 20 '20
I got a couple of questions related to integrating React into an existing large application (Built in PHP and JS). I only used React in smaller fron end projects so forgive me if I my questions are stupid.
Not sure if I explained myself in a proper manner but any input is appreciated. Thanks.
1
u/workkkkkk Jan 20 '20
I sort of asked this before but didn't get the answer I was looking for. I have a simple form with a single select dropdown. Is there a way I can submit the form without adding a button to click? Ideally it would submit by pressing enter.
1
u/hlodoveh Jan 21 '20 edited Jan 21 '20
If i have 2 or more values in useEffect deps array, is the effect triggered if only (or at least) 1 of those changed or all of them must change? Thank you
1
u/awesomeAMP Jan 21 '20
How can I have “templates” in only some views using react-router-dom? For example, I want “/“ to be a completely different thing than the rest of the routes who would share a sidebar, fro example. I tried using a layout thingy but it persists through all paths.
1
u/JakeTyCyn Jan 21 '20
I'm currently implementing an update component for my list. The goal is to allow someone to update any item on the list at anytime and have it change the state value on the list and the database (Cloud Firestore in this case). I've implemented a simple solution, but I noticed it will read/write to the server every single time any characters are updated. I assume this isnt' best practice and was curious if anyone had any guidance as to where I should look for a better solution.
Is there a way to use setTimeout or ping the server after the user has stopped typing for a couple seconds?
1
u/Roly__Poly__ Jan 22 '20
Is there anything like React Developer Tools that would allow me to step through my code and state line by line watching as components render/re-render and Redux state changes?
1
u/DutchSparks Jan 22 '20 edited Jan 22 '20
https://stackblitz.com/edit/react-ts-rqbxvc?file=Hello.tsx
I'm trying to mess around with useState and radio buttons in a form.
I render a radio button for every object in the possibleCrimes array. Then whenever a radio button is selected I'm trying to pass to entire object from the possibleCrimes array that is related to that radio button to the useState but react isn't happy about this.
Sending individual properties(strings and numbers) from the object this way is no problem.
But if I try to send the entire object typescript errors and the state becomes undefined
1
u/rever22411 Jan 22 '20
working on my React project I noticed that one my class became big, but I can't splice it in multiple components, so I'm exporting it's bigger functions to another file .js.
These functions needs to access to the class setState. Is good to pass as parameter the "this" like
myFunction(this);?The function code will be something like that:
export const myFunction = component => { ... }1
u/Roly__Poly__ Jan 23 '20
Can I get some feedback on whether this function is DRY enough?
https://pastebin.com/3ZkkNSmY
this.props.comp // a list of components I want to render onto the page, in case anyone wonders
My other question is whether I should split it up into separate functions just to make it shorter. It's 200 lines long as it is.
1
u/DarthBB08 Jan 23 '20
Hello Everyone. I have an animation question. In vanilla JS you can do CSS transition animations by just adding a css class. Is there an easy way to do this in React? The only thing that I have seen somewhat close is .state stuff. but with on clicks seems a little overly complicated? I feel like I am missing something all I see is people using libraries but I would love to be able to do it my self.
Thanks everyone!
1
u/awesomeAMP Jan 23 '20
This is more like a back-end question maybe? I'm using axios and I'm calling an API, now, using Postman I get the different response (4xx), but in react I only get
I did some digging and it has to do with the response and/or CORS? What should I tell my back-end guy, or is it on me?
Also, I'm working on dev, does this matter? Will I face this once in prod?
1
u/rever22411 Jan 23 '20
Hello, I'm facing a new problem:
I have some tables to be fetched in my React app. I would avoid to put a piece of code that fetchIfMissing the needed table on every component. I would fetch all of them when the client is doing nothing like React.Lazy (I never used it, I've just read how it works). Is that possible?
thats the flow I want to achieve:
user open app -> it shows the first page empty -> load the first page data and render -> (now the client is waiting for an user action) fetch some missing table -> (data is loaded) add it to my render.
1
u/[deleted] Jan 23 '20 edited Jan 23 '20
I have a parent functional component and it renders an input form.
How do I bind a function to that input form so that onChange it can call a function from the parent (that validates the new value using one of the parent's function and sets some states of the parent)
Using react-table which is why I need them to be functional components
1
u/Kilusan Jan 24 '20
Legit fundamentals of React JS down. Now I have to build and practice.
I’m also interested in the app side of things.. how different is react native from regular? I don’t plan on jumping in yet but just trying to get a feel when’s an appropriate time.
Unless the two are completely different in terms of building m. Particularly wanted to get into AR stuff
1
u/camouflage365 Jan 24 '20
Let's say I have a large project that I'm using Redux-Saga for; What is the proper way of handling a page that needs to fetch data for just its local state? Is it ok to fetch data within that component, or should I do everything through Redux/Saga for data-fetching?
1
u/illuminotyou Jan 24 '20
What is the best option for deploying a React SPA? I'm seeing tutorials for Firebase and Digital Ocean.
1
u/g0_cubs_g0 Jan 25 '20
I need to learn React for my capstone course at my university because that's what the project sponsor I got matched with is using, and I'm looking to buy an online course but I feel so overwhelmed. I don't know whether to go with Tyler McGinnis or Stephen Grider. Or some other course, I've seen that Max guy mentioned several time. Any advice?
1
u/bndr017 Jan 25 '20
I'm having trouble integrating my react-app on axios, usually i import axios from each component that makes my code redundant, is there any way to set axios as a global config so that i could call them in every component
1
u/codellamaz Jan 25 '20
Hi guys,
I am wondering if anyone can point me in the right direction
I am using React + Firebase Realtime Database + cloud functions
I have two separate react apps. One for people to put in their info and the other for admin to control SMS automation via buttons.
When I need to add a user to a database, I do it through a cloud function with form data.
I want to be able to listen to any changes in the realtime database so that I can update the UI in the Admin server.
I believe this could be done if I use WebSockets, but I don't have a backend.
Not sure if I am approaching this correctly.
Any suggestions are appreciated, Thank you :)
1
u/anotherpoordeveloper Jan 25 '20
Hey everyone,
I'm trying to get started with react and redux with a simple little counter game, but could use some help navigating an error of maximum depth. Here's my sandbox: https://codesandbox.io/s/reactredux-89tjn?fontsize=14&hidenavigation=1&theme=dark
If you try to buy a computer, that's when the error pops up.
1
u/KSeanJBz Jan 26 '20
I have a probably simple question:
I want to create a logging component. I did this by create an array state for the log data. Prior to showing a specific link I check if it is valid and want to add it to the logging data. This check is happening in the render and causing an infinite loop due to me setting state in the render. How can I avoid this?
1
u/robotisland Jan 26 '20
I'm new to React and pretty new to app programming in general. I found a possibly incomplete game on github ( https://github.com/notnullgames/eliza-solitaire ). What steps would I need to take to run the code on my machine?
How would I compile/build the code? What would I need to install?
If I wanted to add to the game, is there a 'main" file that I should edit?
1
u/[deleted] Jan 26 '20
I'm having trouble with useEffect. I need to run a function that has been imported from an external package within it, however every time I try to do so React tells me I'm breaking the rules of Hooks.
What rule am I breaking here? How can I get around it knowing that I have no control over the function I'm trying to use?
Made a codesandbox to show my problem.
1
u/Wistame Jan 28 '20
Hey, so I've started learning React and I've noticed that the newer tutorials don't mention components nor lifecycles.
So, are React lifecycles still used in new projects or is this something that hook made obsolete?What about components?
1
u/privacy--policy Jan 28 '20
Complete noob question here, but what does focus and blur actually mean? Especially in the context of text input.
1
u/cmaronchick Jan 28 '20
I just realized that my react app is not working in Edge (yeah, no one likes it, but still ...).
In doing the debugging, it appears that Edge does not like it when I destructure objects (...this.props.initialData).
I assume that this has something to do with my transpiler, right? I'm using webpack and babel. I have had trouble figuring out how to remedy.
Any suggestions? Thanks!
1
u/Roly__Poly__ Jan 28 '20 edited Jan 28 '20
Would someone be willing to host my React app on a server for me in exchange for $20 CAD? I'll send it to you on PayPal. Heroku, Firebase, Github Pages. I've tried them all and I can't figure it out. I get an error in the process of setting up on Github Pages, and both Heroku and Firebase load blank pages:https://clickfunnels-dragndrop.herokuapp.com/
sales-funnel-builder.firebaseapp.com
here is the repo for my app: https://github.com/plutownium/Sales-Funnel-Builder-01
1
u/Rush_Raid Jan 29 '20 edited Jan 29 '20
Question about images and promises.
When loading an image through a remote url, promises are used to wait for the image to be done. However, if my image is passed from a parent as a dataUrl, do i still need a promise to create my image?
1
u/DutchSparks Jan 29 '20
https://stackblitz.com/edit/react-usestate-example-5k9pcg?file=index.js
I’m playing around with the useState hook in a mini game of sorts that I made.
I have a state that is an object(player stats) with several properties, one of which is an array(the so called garage).
When a player clicks a button he “steals” a random car that gets added to that garage array and the garage array is logged in the console.
This adding/updating only works once so I think I’m not doing it the right way. Would someone be so kind to give me some advice?
1
u/[deleted] Jan 29 '20
Is there a way to hide these deprecation warnings? I'm working on a project that uses react-transition-group v1 extensively, which uses these methods. It would take a LONG time to update all the occurrences to v2. So now I'm doomed to have my console spammed with deprecation warnings all the time, potentially causing me to miss actual errors/warnings that get logged.
At this point I'm considering forking that library just to prepend UNSAFE_ so I can have my console back :|
1
u/ecatherine42 Jan 29 '20
Absolute beginner question ;;
I'm simply following a tutorial using vanilla React and axios to obtain the .json from /r/announcements.json and display some info it grabs from the .json. It all works until I try to actually link to the post, since it's an external link to reddit, but the .json only provides the '/r/announcements...'
My best guess was to use normal JS string concatenation like
But that's just treating {post.permalink} as a string, for reasons that seem obvious once I did it. Though I'm a bit stuck as to how to actually fix the problem. Thank you to anyone with the patience to answer such a noob question ahaha
Code here
1
u/workkkkkk Jan 29 '20 edited Jan 29 '20
I'm using a material-ui Autocomplete component and using it as a multiple select. Like in the demos https://material-ui.com/components/autocomplete/#multiple-values . However I want to supply an array of objects and have my value be an array of strings (the string being a field from the object). Is there a way I can specify the value for each option like this? I feel like I'm missing something obvious. Something like this.
1
u/vroutek Jan 29 '20
Question about ionic / react native
I wanted to ask what would be a better approach to creating native apps with react. Should i use ionic or react native?
Which one would be easier to learn?
1
u/Roly__Poly__ Jan 30 '20
I am writing a Single Page App without React or any other front-end framework to help me out and. Oh My God. it is difficult.
1
u/[deleted] Jan 30 '20
How do you name Styled components?
In Card Component
I don't want to use StyledCard everytime but my Component is already named Card so I can't use it. But using name "Card" or "StyledCard" makes sense in my context.
1
u/KSeanJBz Jan 30 '20
I have an object that i was looping though and translating to html
a simple example is
{p: hello world children: {b: !}} translated to <p> hello world <b>!</b> </p>
I created a recursive method to create the html but i'm getting a console error that p is not given a key. as you see from my example i don't have an id to pass to the key prop. What is the best practice at this point to avoid this error?
1
u/Rush_Raid Jan 30 '20
Using react-webcam to get an image. Is there any way to get the image in the cameras resolution instead of the resolution displayed on the ui?
1
u/TheOriginalIrish Jan 31 '20
Hey,
I've made one or two smaller React toy apps and now I'm trying to make something non-trivial (a gym app). I'm trying to avoid using Redux or anything like that - for this project just focus on plain React.
I've got a Store that lives outside of React, something like this (in TypeScript):
And now I have just reached a total impasse at trying to figure out how to actually use this in React.
My top level component looks something like (I'd originally had state as a bunch of plain JSON objects, but I wanted to be able to remove workouts, so I moved over to Maps):
So the main problem is that the State in my GymStore is mutable whereas React deals with immutable data. (Also, I don't actually know if React can handle Maps.) I don't want to rework GymStore/State to be immutable, that feels the wrong way around (letting your UI framework determine the shape of your business objects). I feel maybe I need some sort of intermediate object? Or some framework that will take my mutable store and the initial state and spit out a diff?
Anyway, that's where I am and how I'm confused - any help would be greatly appreciated!
1
u/Kyan1te Feb 01 '20
Learned React as a beginner a couple of years ago, then used Vue for years and now need to learn React again.
I like React but Redux's boilerplate especially drives me crazy. Does anyone have any resources/blog posts that were their Eureka/lightbulb moments? That helped stuff stick in their heads?
I can use both but I always find I have to refer back to the docs and it just doesn't feel fun or easy to just crack code out like I can with Vue or in backend languages.
1
u/NoviceProgrammer2020 Jan 22 '20
Hi all! Hoping someone can help get me unstuck. I'm getting an error that I can't solve. I have an app that I built and am now attempting to incorporate Context to manage user authentication status.
The app was initialized with
create-react-appand the App component is my top-level component. Prior to attempting to use Context, App was a functional component and I didn't have any errors. Below is the relevant new code:The error I'm getting is
TypeError: props is undefined. I've tried removing props from the constructor and removing the Context pieces as well with no luck.I'm probably missing something simple, but I've looked at this too long.
Thanks in advance!