r/reactjs • u/dance2die • Nov 01 '20
Needs Help Beginner's Thread / Easy Questions (November 2020)
Previous Beginner's Threads can be found in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! We’re a friendly bunch 🙂
Help us to help you better
Improve your chances of reply by
- adding minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- 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. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! 👉
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
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!
17
Upvotes
3
u/talohana Nov 01 '20
Where you draw the line between smart and funny component? With consideration of hooks and testability of components - for example components who use context API
2
u/zNareak Nov 01 '20
Hello, I'm new to reddit, I signed up here to ask a series of unknowns, I can see that there is a better reception to programming issues.
In this case I have a problem in Reactjs, it is the typical problem of updating a disassembled component, it usually happens to me in asynchronous requests in container components, which render views.
How can I avoid this behavior?
I have read about anti-patterns like "isMounted", cancel the request before dismounting, among others. However, I made the decision not to use those alternatives, so I ask for help to know how I can improve my asynchronous requests so that this error does not occur and I do not lose performance.
Where should I put my status so that this error does not occur?
How to avoid that mistake?
Am I on the wrong track if those kinds of errors appear often?
Thanks for reading, and if possible for answering. :)
2
u/[deleted] Nov 01 '20
How would you link JavaScript components through clicking on an element in a menu without react router, for example lets say I had something like this in a JavaScript file
And after clicking the button I want another Js file to be output - how would I go about this?
2
u/al_vo Nov 04 '20
Is the Suspense API out of 'experimental' yet? Is there a hint on when this will be available - it's been talked about for a few years now?
1
u/[deleted] Nov 11 '20
Anyone have any advice on switching from Angular to React professionally? I have some experience building small pet projects in React but have a year and half of professional Angular experience. I'm currently taking an advanced JS course right now but after that will probably take a React course. How would I list on my resume that I'm looking to switch over? My main reason for switching over is it seems that React jobs are more abundant at least in areas I'd (eventually, COVID-dependent) relocate to.
1
u/AckmanDESU Nov 11 '20
I questions regarding state management.
So far I've always tried "lifting the state up". That is, keep all the state on the root component and let every other component work exclusively through props.
My two questions are:
Thanks for your help guys
1
u/rony_ali Nov 11 '20 edited Nov 12 '20
Hello everyone
i want to display every error messages from Django Rest Api automatically in React frontend. i wanted to test my concept with the signup authentication function and after fixing it i would like to use the concept in every components in fetching data from or into django API.
here is my App.js to register a user just for test:
in UseEffect i have tried to show every error message under relevant input boxes which are username, email, password1, password2, i tried to do it by React-hook-form but it will be like inserting error messages from frontend. but i want to show actual error messages from backend. in development tools, when i try upper codes by putting wrong infos in input boxes, it would only show POST: 400 (bad request)
how can i show such error messages under every input boxes like Username exist or email address is invalid, or password must be at least 8 which are typical in Django Rest API's typical error messages ?
FYI: this code can register any user if the input boxes are correctly filled up.
1
u/[deleted] Nov 29 '20
What is suggested to build a radar app in react that detects points. What I know is react-radar-screen package which is pretty old(last published 4 years ago) and wants me to use the react version of what it was then. I am a newbie and don't want to experiment this much now. What other packages can I use to achieve this plus if not how should I use this older package.
2
u/fpuen Nov 01 '20
I notice i can't declare variables inside a JSX escape:
Based on the error lint statements aren't allowed, only expressions that evaluate down to a single value, is that correct?
2
u/reactyboi Nov 01 '20
Maybe an obvious one, but how can I do this - given a variable called
tagwhich will contain a string like"h1"or"p", how do I then write JSX to end up with the corresponding html element?e.g. if
tagcontains"h3", I want to end up with<h3>Hello world!</h3>2
u/TamingSpyro Nov 02 '20
I'm questioning where I should storing my data. I have a Post container with tags, section headers, and comment components. The section headers needs to know how many comments there are so it can indicate if there's comments on that section; neither tags or comments are shown at the same time. Should I store my comments in the container, or should I store it in the component itself? The problem I'm running into is that my section headers doesn't know how many comments there are until the comments section is loaded. When it does load, I'm loading my comments from the database and then sending them to the post container, which sends it to the section headers component. What's the right way of doing this?
2
u/tuoPadreNaked Nov 10 '20
Hi all, It seems i can't understand how to do conditional rendering in this scenario: I have a picklist where I select a value; based on the selection of the picklist (which is in a component) i want to render a form. How can I achieve this?
Thanks in advance
1
u/micky04 Nov 01 '20
How small/specific should a component be? Say I create a Twitter clone and there is an input form with a text field and button. Should those two be components wrapped inside an input box component, or should I just have one fat input box component?
1
u/Roci89 Nov 01 '20
Using a framework like Material-UI or Ant Design, is it bad practice to render things like drawers and modal components in a loop, like say extra actions in a list?
1
u/badboyzpwns Nov 02 '20
I've read around and found out that people use Next.js/Gatsby over Create React App for SEO purposes. But! is it possible to make a CRA 's SEO that is on par with Next.js/Gatsby? Say you built a site that didn't care about SEO, so you used CRA. Then later down the line, you really do care about SEO. What do you do?
1
u/stfuandkissmyturtle Nov 02 '20
I've landed a really cool internship where they want me to build a front end for an app that's going to be widely used. It's something like a market place for small businesses. My excitement has now turned into a worry about if I'm good enough. Any tips to make me feel better and not completely disappoint everyone ? I'll be working with an experienced back end dev and another experienced front end dev but he'll be mostly as advisor
1
u/tRickliest Nov 04 '20
What is the correct way to have a button trigger the scrolling down to a component on the page, if both these components are in completely different parts of the DOM tree? I have a table on the right, and if I click on the date in that table I want to go down to the thing of that date further down the page.
I have read about refs, but the two components are so far from each other that passing the refs between them makes no sense, should I be storing them in some shared state or is there a more conventional way to do this?
1
u/rreeaaccttiivvee Nov 04 '20
How important is accessibility when looking for a job?
Should I invest my time into learning accessibility, or perhaps spend my time better elsewhere?
1
u/un_H_nu Nov 05 '20
how should i handle a design with nested input component, for instance, if i have a 'Person Info' section, and in it an 'Address' section, which i want to have its own component, but it's impossible to nest JSX Forms, right?
1
u/kyds3k Nov 05 '20
I have a bunch of divs one after another, each has a className "slide" and "slide-#" (where the # goes from 1 to however many there are). They also have className "active" or "inactive" depending on if I want them to show up. I'm using "react-hotkeys-hook" which lets me assign things to keys, so I'm hoping to be able to press up and down arrows to iterate through the divs - basically, down will change all divs to "inactive" then change the next div in the stack to "active". What's the best React-y way to pull this off?
Sandbox: https://codesandbox.io/s/agitated-tharp-1r6f4?file=/src/App.js
1
u/TamingSpyro Nov 05 '20
I don't know the terms to ask this, but I'm trying to gets post entries from the back end, and then filter it by tags entered by the user. Right now I'm doing something dumb by getting all posts and then filtering it on the front end with tags. What's a better flow for this so more of the work is done on the back end, and what are the terms to research this? I was thinking of changing the action to get newest posts determined by a Redux variable for amount of posts the user can see. There's infinite scrolling, so scrolling would increase this variable, and then I get all the amount of posts by that variable when its changed. But is there a way to say, get the first 20 on initial load, and then 21-40 on scrolling, and then 41-60? Or is that a bad way of doing it?
1
u/stfuandkissmyturtle Nov 05 '20
const [value, setValue] = useState(0);useEffect(() => {console.log("useEffect renders");if (value >= 1) {document.title = \new message(${value})`;`}}, [value]);Im learning useEffects baics and from what I understand the useEffect hook will only run in this case if I provide a value in the dependancy array. However if I pass something like [value +5] it still runs as intended. Any reason why ?
1
u/fireflux_ Nov 06 '20 edited Nov 06 '20
What's considered "best practice" for handling remote fetch calls?
What I usually do:
1
u/enz3 Nov 06 '20
Hey! I just started looking into react. My doubt is this, I don't have prior experience in any of the web stuff. I know Python and Go. Should I be using all the different Bootstrap , reactstrap stuff for making sites or should I manually work on them?
1
u/BeerAndBall Nov 06 '20
I have decent experience in HTML & CSS, and know a few things here and there about vanilla JavaScript. Should I learn JS first or can I jump directly to React?
1
u/semprotanbayigonTM Nov 06 '20
Is it required to know about ReactJS before learning React Native? I looked into Grider's React Native course on Udemy and it says the prereq is only the "basic understanding of JS" and doesn't mention ReactJS at all. What do you think?
I know some basic JS but have never touched front end framework before. I mainly do simple web app using Flask for my ML deployment.
1
u/whatismyusernamegrr Nov 07 '20
I haven't kept up with react since about 16.8. I think the last thing I have learned are hooks. What are some good things to read to catch me up to 17?
1
u/xjellyfishx Nov 07 '20
Beginner here need help with state.
Basically I have checkbox items that captured into state by Redux.
Problem is during check/uncheck the state is not updated inside function but outside of function shows updated state
1
u/ricocotam Nov 07 '20
Hi ! Thanks for the thread
I'm new to react/web dev and i'm facing a quite interesting problem. I'm trying to develop a basic note project. Features are :
So I code the whole thing and when I click on a note, it works ! But then I click on another note and nothing changes visually though I can see using React Debug Tool that the component AND HTML actually changed. Which really weird.
Here is my github and a sample of the code doing the switch :
thanks for your help !
1
u/lrningprogrammer Nov 08 '20 edited Nov 08 '20
Hi,
I have been working with React for the past couple of months. I wanted to ask, why would someone use styled-components or CSS in JS to style a React component? Isn't it much easier to have your CSS styles, for example, in a centralized CSS file in order to make style changes easier? What are the advantages of stylizing components in either the component itself or a JS file for the component?
Thanks
1
u/[deleted] Nov 08 '20
What do the dots in imports actually mean, such as the 2 dots before in this 'import search from '../components/search' ? Is it just a reference to the src?
1
u/DoujinProject Nov 08 '20 edited Nov 08 '20
How to install Watchman on Windows 10?
The instalation guide says that it contans bin folder, but I dont find it
https://facebook.github.io/watchman/docs/install#windows
Can anyone help me?
1
u/badboyzpwns Nov 12 '20
I'm having a typescript issue with redux-form and compose. To use compose with redux-form. It looks like you need to add a generic of <React.FC> or <React.Component> together with compose, such as below:
AuthForm.tsx
It works!
But! this gives me another error because I have my own onSubmit props. I've commented on the error below. Any ideas on how to fix this?
Body.tsx
1
u/danroche10 Nov 12 '20
Hey folks,
I hope you're all well.
I would be so grateful if any of you can shed some light on the following question..
There are two relevant components:
2. Child component called 'AuthorCard' (you can see placed in the parent component above):
The issue is as follows:
When I click the as={Link} to={`/essays`} button in the child component, I would like to 'setWriter' state to the individual Author whose button I am clicking on.
However, I am not able to specify the individual author whose button is being clicked on. React thinks I want to 'setWriter' for the entire list of authors. For example, when I console.log(Author) within the button, I can see every author in the list printed in the console.
I have tried adding id, using event.target .value, and onChange instead of onClick.
I just haven't been able to target the individual author in order to update the state (which will be needed in a different component).
Please let me know if anything isn't clear or if it would be helpful to provide more details.
Thanks in advance and happy coding!!!
Dan
1
u/IamNobody85 Nov 12 '20
hi people! I am using the
useState()hook to empty out an array. How do I immediately check if the array is empty or not? checking forarray.lengthis always one iteration behind, similar to justconsole.log(array)and the parent
handleChangehopefully the formatting is ok, and my problem is clear. I can't produce a full example, because this is one complicated component. Thanks for any help!
1
u/b1100 Nov 12 '20
Hi,
I am working on a basic list app, and want users to be able to share their list and allow others to edit it as well. Is it bad practice to show the user the Firestore ID to share to friends?
In theory, the flow would be:
1
u/Chthulu_ Nov 12 '20
I've got a fairly sizeable app for a first-timer. React+Redux with hooks. I'm getting close to launch, but the performance of my app is struggling. Some actions a user can take causes the entire app to update all at once, with dozens of network requests and a complete rebuild of the redux store with lots of financial data processing. The memory shoots up for 4 seconds, and any animations start to hang.
Does anyone have good resources about how to diagnose and fix performance issues? I feel pretty out of my depth here, I'm usually more focused on coding for convenience rather than performance. If I were to replicate this app with plain JS (ignoring all of the UI difficulties that would come up), I know the amount of data I'm working with wouldn't cause a slowdown. its my React implementation thats the problem.
I've got a handle on memoization, but I don't think that will fix it completely. It appears that rendering step is whats causing the slowdown, so I need ways to cut down on the number of renders anywhere I can. The problem is, some components really do need lots of selectors and lots of state. I know that will shoot up the renders for that component, but I can't see a way around it.
Any ideas where to start? Any more advanced design practices that keep performance in mind? How to really data-intensive enterprise apps pull it off?
1
u/[deleted] Nov 13 '20
I learned React recently & I was wondering what would ve a better investment(job wise) to go and learn a state management library like Redux or Mobx or instead start with Typescript first and then move to state managamente library?
What are your thoughts?
1
u/Chthulu_ Nov 13 '20
In most situations it’s the latter, the state is pretty independent, components only update when they need to. It’s just this one situation where I’m rebuilding the entire UI with completely new data. It feels like a page load almost, everything has to get thrown out and updated again. Once that happens, the app is back to normal and snappy for whatever the user wants to do.
Another problem would be that some components require data merged from multiple endpoints. So that component ends up updating each time one of the data sources does. And to make it worse, these sources need to be stored separately. Component A might use merged data from endpoint 1 and 2, and component B might use merged data from 2 and 3. It just makes sense to keep each data source separate in the store.
I can’t avoid this reload from happening, so I see a few solutions.
1
u/mcgovec9 Nov 13 '20
Hi all, had a question with regards to state and props, I am new to React so apologies in advance if my question doesn't make much sense.
I am designing an analytics application. Lets say for example on one page, the analysis page, its props will contain a list of clients and their data, and on the page itself there are charts/table which display this data.
Also on the page there are filters, such as a client filter, a month/year filter etc. when these filters are changed, the data in the tables/charts should be filtered also.
My question is, can this be achieved in a stateless component? the component i'm referring to is the 'analysis page' component. Its props would contain all the data needed, but could you just manipulate what props get passed to the tables/charts show based on the filters and just refresh the elements, without having to introduce state?
1
u/tuoPadreNaked Nov 13 '20
Hi everyone,
I was wondering if there is a way to dynamically add, for example, an input box and a textarea;
Let's say i already have an input and textarea and a + button: onClick on this button i would like to add and render additional input and textarea.
Any suggestion on how can i achieve this?
1
u/fireflux_ Nov 13 '20 edited Nov 13 '20
Assuming I'm not using redux, where's the simplest/cleanest way to manage remote data? Things like
I'm building a DataTable component with filters and forms (update rows, filter, pagination, etc). I've been thinking of using a large DataProvider that holds multiple tables worth of data, i.e. table1Data, table2Data..etc. But it feels repetitive. I also don't want to call
fetchon the TableComponent itself, because I might need to access parts of that fetched data in other components (ex. a Form component).I've heard about vercel's
swrandreact-query, are those a better tools than Context in this case?Here's roughly how I have it set up:
1
u/kingducasse Nov 13 '20
I'm expecting
updatedCustomersto come back as an array except I getundefined. Using Sequelize as my ORM for MySql which returns a Promise for every db.Model.method.The logic is that I first search
db.Seatingsfor whatever get's sent in via client request. Then it checks if row returned (seating) has true or false for it'sactivecolumn. If false, it should updated the row'sactiveto true and it'sbooth_idto whatever gets sent in via client request. It should also updated all of thecustomers's array associated to it, where eachactiveproperty should be true.Like stated above,
updatedCustomersreturns as undefined even thoughupdatedSeatingsreturns the updated row. Any advice or something that I'm missing?1
u/Lukasvis Nov 13 '20
Hi guys!
I have set my initial state object like this:
const [Item,SetItem] = useState({description: "Chicken",foodNutrients:[{nutrientName: "Protein", nutrientNumber: "203", value: 10},{nutrientName: "Fat", nutrientNumber: "204", value: 15},{nutrientName: "Carbs", nutrientNumber: "205", value: 20}]}I want to modify my existing object by looping through foodNutrient array and doubling the value on button click, then storing the updated object in useState hook.
const Double = e => {SetItem(Item.foodNutrients.forEach(foodNutrient => foodNutrient.value *= 2))console.log(Item)}Why do I get
Cannot read property 'foodNutrients' of undefined1
u/_class_ Nov 14 '20
I'm new to React and I'm creating an app with Firebase auth (along with FirebaseUI, if that matters). I would like to be able to reference some of the user auth data in other areas of the app, ie. if a user is authenticated, display the user's profile pic in the navbar. What is/are the best React-ish options for doing this? I read a little about lifting up state - that seems pretty straightforward. Also read a little about state management tools like Redux but for this task that seems completely unnecessary. And I saw for Auth0, there are 3rd party modules that provide a hook to the user auth data simply by importing the module. I imagine there's something similar for Firebase but I wonder if this is simple enough to create yourself.
1
u/daryllman Nov 14 '20 edited Nov 14 '20
How can I create a 'Click/Drag and Select' Interface in React?I am trying to create a side project that is similar to when2meet & lettuce meet and both web apps have a simple drag to select the timings when you are free (where the timings are boxes - view the link and you will know what i mean).Was wondering how I can create such an interface in React. I dont think I found any resources or sample code sandboxes around:(
I will be able to:
1
u/kingducasse Nov 15 '20
This is probably something small and dumb, but I can't return a value from a child stateless component to a parent stateless component. What am I missing?
My **handleModal** function in my child component isn't setting the state in it's parent component.
1
u/Street_Theory Nov 15 '20
I’m doing onmouseover and onmouseout to switch the styles. It works in regular html/css, but it’s not working in react. Why aren’t the onmouseover and onmouseout working? How do I fix it??
1
u/tuoPadreNaked Nov 16 '20
Hi all,
I have made a Form component, in which i render other 2 components (Picklist and ParagraphBox); so parent = Form, children = Picklist and ParagraphBox.
Now i also have a button "+" where i want to add an onClick listner in order to toggle the creation of another ParagraphBox inside my form; so i want to add and also remove n ParagraphBox componets inside my Form component.
Any help on how to achieve this?
Also i'm uising Hooks
this is ParagraphBox
export default function ParagraphBox(props) {const [paragraph, setParagraph] = useState({})useEffect(() => {console.log('Paragraph ', Paragraph)props.onChange(Paragraph)}, [Paragraph])const onChange = (e) => {const titolo =e.target.nameconst contenuto = e.target.valuesetParagrafo({...paragraph,[titolo]: contenuto})}return (<div className = "paragraph-box"><label>{props.labelInputBox}<div><input type="text" name="titolo" value={paragraph.titolo || ''} onChange={onChange}/></div>{props.labelTextArea}<div><textarea id="subject" name="contenuto" placeholder="Inserisci contenuto.." style={{height: "45x", width: "400px"}} value={paragraph.contenuto || ''} onChange={onChange} /></div></label></div>)}Here is my form component:
export default function Form() {const [flagImg, setFlagImg] = useState(false)const [flagPar, setFlagPar] = useState(false)const [paragArray, setParagArray] = useState([const handleChange = (e) => {setParagArray({}useEffect(() => {}, [flagPar, flagImg, paragArray])const handleSubmit = (evt) => {evt.preventDefault();}const addParag = () => {//HERE I DON'T KNOW HOW TO DO ITconst onSelect = (selectedValue) => {if(selectedValue === 'Layout 2') {setFlagImg(true)setFlagPar(true)}}return(<div><Picklist onSelect={onSelect} label="Seleziona un layout di contratto: " pickVals={["Seleziona...", "Layout 1", "Layout 2", "Layout 3"]}/>{flagImg ? (<form onSubmit={handleSubmit}><Picklist onSelect={onSelect} label="Seleziona Immagine: " pickVals={["Seleziona...", "Immagine 1", "Immagine 2", "Immagine 3"]} /></form>) : null}{flagPar ? (<div>{addParag()}<div id = "add-paragraph"><button type="button" onClick={addParag}>+</button><input type="submit" value="Submit" /></div></div>) : null}</div>)1
u/Chy226 Nov 16 '20
hi everyone, i wanted to convert 2 files with class components into a functional component. This is the first file:
this is the second:
Im not sure how as I've never converted something that extends it components.
1
u/NoEstablishment6817 Nov 17 '20
import React from 'react';
import { SafeAreaView, StyleSheet, View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const SecondPage = ({ route }) => {
return (
<SafeAreaView
style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.heading}>
Yeah , we got this value from first screen
</Text>
<Text style={styles.textStyle}>
Values passed from First page: {route.params.paramKey}
</Text>
<Button title="Go to Home" onPress={() => navigation.navigate('FirstPage')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
<Button
title="Go Next"
//Button Title
onPress={() =>
navigation.navigate('ThirdPage', {
paramKey: userName,
})
}
/>
</View>
</SafeAreaView> ); };
export default SecondPage;
error is that not working two BUTTONS go BACK and GO home
1
u/giantqtipz Nov 17 '20
hello,
I'm noticing for the first time that on the homepage of reddit, or main page of subreddits, the vote and comment counts of posts are updated live.
I don't remember if Reddit is built with React; but are the counts changing because a get request is made every few seconds; to update the counters?
thanks!
1
u/VelaLover69 Nov 19 '20
Hello, how can I wait for multiple asynchronous calls to finish? I'm looking for a solution without async/await if possible.
I can't figure out how to wait for multiple fetch, as I can't just chain them with .then()
Is Promise.all() the solution? As of now, I just update the state inside the fetch(), which seems to be working but looks wrong.
1
u/Niesyto Nov 25 '20
I have a component, let's call it A which fetches list of images from the server, and then displays all those images with:
<img src={*single image from list*} />I can see that it sends network requests for the images at first render, but it does not after a re-render, or when I render another instance of this component.
Are those images automatically cached somehow? I'm not doing it, but it seems to remember the images were fetched, and does not send another request for them
1
u/[deleted] Nov 27 '20
What is suggested to make the view front end with reactjs? I saw people are using nextjs? Any suggestions and why are people using nextjs (ELI5)
---
I currently have a full stack with expresss for backend, but I haven't started on the views /front end yet
1
u/ebwaked Nov 01 '20
So I finally was able to get a hello world working using webpack, Babel with my existing asp.net mvc 5. What steps do I need to do to add typescript and should I be using yarn over npm? I think tor typescript I just add the proper packages and update some config files and I should be good to go right?
0
u/RDTIZFUN Nov 03 '20
Can someone please help me understand (ELI5) the following 'things'
Redux React Router Next js Nest js Apollo Hooks Context API XState Suspense Socket IO React Query Gatsby MobX Lambda Serverless Functions Recoil
Sorry if they seem all-over the place. It would be great if you can categorize them and put similar together and rank them in popularity, if possible.
I know basic html/css/js and while surfing medium, these are some of the buzz terms that stood out.
Thanks in advance.
0
u/Gagsterrent Nov 05 '20
do you know you can create rich and user-friendly web interfaces and applications using Jexcelwith react
0
u/[deleted] Nov 05 '20
[deleted] — view deleted comment
1
u/[deleted] Nov 29 '20
[removed] — view removed comment
1
u/[deleted] Nov 14 '20
[removed] — view removed comment