r/reactjs • u/timmonsjg • Aug 01 '19
Beginner's Thread / Easy Questions (August 2019)
Previous two threads - July 2019 and June 2019.
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 or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- 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.
Have a question regarding code / repository organization?
It's most likely answered within this tweet.
New to React?
Check out the sub's sidebar!
🆓 Here are great, free resources! 🆓
- Create React App
- Read the official Getting Started page on the docs.
- /u/acemarke's suggested resources for learning React
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
•
u/timmonsjg Aug 02 '19
Just a heads up that /u/dance2die will be hosting our September Beginner's Thread :)
If anyone else is interested in hosting / has other ideas for this thread, please feel free to comment or reach out!
2
u/joalcava Aug 05 '19
I just finished migrating a pretty complex class component to functional one, using react hooks. I've notice a difference that made me question myself if i'm doing it rigth.
The difference is this: My class component reacted to a changes by computing a lot of logic and updating state once (and rendering once). My functional component 'react' to a change by doing small pices of logic but chaining the updates (and rendering many times).
Off course that's because i'm using many small effects, but is it supposed to be that way? or should I make a fat effect?
I'm not too concerned about performance, the page is fast and the total number of renders is 5 to 8 depending on what the user did, but I'm a bit obssesd with that and I always try to optimize renderings.
4
u/Dfree35 Aug 04 '19
This may be the wrong place to ask this but how do you pass a variable(?) to another component/file?
For example: This file has {game.name} and I am trying to use that game.name in another file.
I want to use it in another file because I am using react-share and I want to use that game.name so the games name can automatically be populated when shared.
Any advice or anything I can read to point me in the right direction would be appreciated.
1
u/Axel737ng Aug 01 '19
Hi guys, first time posting here so I hope it's not the wrong place.
I'm creating an app using nodejs, graphql and reactjs. The goal is to have users login, upload pdf documents, store them in the server local drive (it's a small business internal app) and eventually have people either approve or request modifications on it.
So far the progress has been good, I managed to handle the upload and record the path and files data into the database.
Now the part that is making me struggle for some reason as I'm not sure how to proceed: when I display the record I want to create an online preview but I'm not sure what to use to accomplish that, I know that nodejs can "send" a file for download but I would like instead to have it displayed in a component.
So is there something or someone out there that might point me in the right direction?
Thanks in advance to anyone whose going to reply!
1
u/Niesyto Aug 01 '19
I've heard that Hooks can make components more reusable. How so?
1
u/jadenzuko Aug 01 '19
I need clarification on event handling, onChange, and onSubmit. Right now, I have a parent component that passes state to a child component as props. After the user enters the relevant information, they execute the submit button. When thinking about it, there shouldn't be a need for an onChange attribute because the onSubmit attribute should take both inputs and set them to their corresponding values in the Parent component. However, when I checked to see if the submit was changing the state of the Parent component via setState, it didn't. Do I need the onChange attirubute and if so, do I pass those input changes to the onSubmit function so that it can then pass it back up to the parent?
https://codesandbox.io/s/submission-form-test-3q9zl
1
u/badboyzpwns Aug 01 '19
Why are service workers turned off in Create React App with
serviceWorker.unregister();? React states that by turning it on causes some pitfalls. But are the pitfalls really crucial? All I know is that service workers enable you to browser cache more efficiently, I don't see how that could create issues,Doc link: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
1
u/SarSha Aug 02 '19
Hello!
I'm a full stack \ front end dev for the past 5 years. Been working mainly with Angular and have good understanding of the JS language.
My goal for 2020 is to transition to React position. What are the concepts (both basic and advanced) I need to work hard on?
I know the concepts of creating components, using state including the useState hook, data flow in component based architectures etc...
Thanks!
1
u/Bylee_ Aug 02 '19 edited Aug 02 '19
Hi everyone, I’ve been taking the online course React Front to Back from Brad Traversy on Udemy and I was hoping to get some help on the second project : the contact keeper.
When I update a contact on the UI, the call gets made to the back-end where the contact gets updated but there is no reflection of it on the UI.
I’ve been looking at both my code and the solution on github and can’t find where the error is...
Anybody took that course and had a similar issue ?
Thanks
PS : I think it might be related to the reducers and the context ?
Link : https://github.com/xsalvatore/contact-keeper
1
u/sharkbot777 Aug 02 '19
new to react here, anyone care to share an opinion or thoughts on facebooks create-react-app vs others such as react starter kit?
are these things viewed by pros as training wheels or legit scaffolding solutions?
1
u/Radinax Aug 06 '19
Hello!
I'm wanting to create a React code that does YouTube Live Streams (like League of Legends LCS), I want to add a comment section but I'm not sure where to being with. For YouTube I used a library called react-youtube and works well (could've used iframe but liked this one), but I'm completely out of ideas on how to import the comments from YouTube :(
I want to make something like this
1
u/TheUserIsDrunk Aug 06 '19
What would be a more elegant way to fix this?
currentUseris coming from the server so there's a small flick if the user is logged in while the page is loading. The login link appears for a few ms before disappearing.I fixed it with a hook:
const [finishedLoading, setFinishedLoading] = useState(false);So in the
<Query>render prop I setfinishedLoadingto true by calling theisFinishedfunction withcurrentUserto avoid the flickering. And then I pass `finishedLoading` to the condition:It works but I think there's a better and more elegant way to fix this. Any idea?
1
u/workkkkkk Aug 06 '19
Is there a way to specify how and where my sass gets compiled using create-react-app? As in if all my styles are in a 'styles' folder inside src when I build can I output two different css files (lightTheme.css and darkTheme.css) that I can switch between at runtime?
What I'm doing now feels very janky. I'm basically just sass --watch'ing a file independent of my project and compiling it to the public folder of my project to have access to it.
1
u/tanahtanah Aug 07 '19
Hi.
Is redux or hooks necessary to build any react app?
I want to build something like he using react : https://youtu.be/go6NnHmFGj4
What kind of technology other than react do i need to do that? It's for a one year capstone project at uni.
My plan is to learn more about react,semantic UI and react spring.
1
u/crespo_modesto Aug 07 '19
Opinion/general info
What is a common practice when bridging ReactJS with Node? Use Express? Up to user depending on their competence/preference? Not trying to write auth/API stuff from scratch but was wondering.
Is CSRF still a thinking when Node serves ReactJS or are they separate still?
1
u/Niesyto Aug 09 '19
Is lifting state up so much easier with hooks as it seems?
https://reactjs.org/docs/lifting-state-up.html
This entire tutorial is obsolete, you can just create a useState hook in the highest component and just pass the hook as a prop to whichever child needs it.
Or am I missing something here?
1
u/Bombuhclaat Aug 12 '19
Hey guys, I did an interview for a web developer job and I got a question that i'm still confused as to how I was supposed to approach it.
"Imagine you are implementing a comment system for Netflix, write the code for adding, deleting & editing comments." "Then add the feature to have audio, picture or text comments"
How would you guys approach this?
Seems like such an incomplete question. Any help would be appreciated
1
u/javascript_dev Aug 13 '19
Is there a way to have React Dev Tools show source mapped code? Right now it shows compiled code: https://nimb.ws/pj3XKz
I can't make sense of its component structure and the state is not accessible either
Partial copy of my webpack config:
1
u/javascript_dev Aug 14 '19
For reasons I forget I needed a Wrapper div around the 2nd level child for everything here to work.
is there a default prop at the react level that would allow me to test whether to display the component? SOmething like this would be nice:
The way I have it now uses
displayBoolto tell styled components to set CSS display to inherit or none.1
u/javascript_dev Aug 14 '19
If you are deleting a table row, is it generally better to remove the affected row from state upon success, or force a component update on success (which requires another db call)?
I wrote my code to delete the row from local state. Now I'm wondering if this is the pattern I should have chosen. Seems like added complexity for no benefit.
On the other hand table modifications that are not deletions may benefit from direct state modifications so I don't know.
1
u/tanahtanah Aug 20 '19
What is the different between using semantic-ui by copy paste the cdn on the html file than installing semantic-ui-react?
1
u/Peechez Aug 23 '19 edited Aug 23 '19
I've hit a bit of a conceptual road block that I think I'm overthinking.
I have a List component with n ListItem children. Each ListItem can be collapsed and has a local state bool to handle it. The List has expand/collapse all buttons to send down as a prop. Each list item then has a useEffect to update its own bool to match the prop.
So far so good right?
If you manually collapse each item then the parent buttons no longer work since there's a disconnect between what the list thinks the state is and what it really is for each individual list item.
I want to confirm that the best (only?) solution for this is to keep the boolean state tightly coupled with each list items id that gets sent down through the app as props. What is the best stance to take on mixing business data from the database and ui data for the front end? Smash it together or separate objects that you keep in sync?
1
u/00101100BendertheRob Aug 26 '19
Hi there! I'm finishing a full stack software engineering internship in about a week and I've learned so much about back end RESTful APIs with springboot in java and kotlin but my react experience is limited to mostly styling changes. I'm much more comfortable with back end development but I want to learn more about implementing back end APIs into react. I have an idea for a local multiplayer game that works similar to Jackbox games where you go to a link, type in a name and game code and play with others. Are there any good resources or tutorials for developing web apps like this? I'm already going through a lot of the beginner resources I've found in this subreddit but I haven't found any resources to help me go from there. Any help would be greatly appreciated!
1
u/fwegan Aug 26 '19
Okay, I'm totally stumped on what seems like it should be an easy problem. I'm making my first React Native app on my own, just a simple life counter for Magic. It consists of two counters that both start at 20. The part I'm stuck on is making a reset button that resets both counters.
What I've got so far: https://codesandbox.io/s/dazzling-brown-xmm6u?fontsize=14
I have each counter as its own component that includes a resetLife() method, but I don't know how to call that when the reset button (another component) gets pressed.
I suspect that I might be thinking about the hierarchy wrong. Any help would be appreciated!
1
u/Herrowgayboi Aug 26 '19
What are some website hosts you can recommend, that allow you to use ads to make money off of your website?
1
u/ViperRT10Matt Aug 27 '19
I am early on my React learning curve and am trying to master calling a RESTful API to get data, then display it.
All the tutorials are pretty similar; I am following this one:
https://pusher.com/tutorials/consume-restful-api-react
I have customized this to call my own API, and with my own display object. Everything runs without error, but my issue is that per Alert statements that I added, my class' render() is being called before componentDidMount(), and since my state is set in the latter, there is nothing to render. My understanding is that the opposite is supposed to be the case?
1
u/Bylee_ Aug 29 '19
Hi everyone, I managed to get and interview for a junior front-end web development and they gave me a coding challenge to do at home.
I managed to finish it a bit in advance and still have a couple of hours before the deadline. I have all the basic functionality they asked me and I was wondering if I should be sending my version as is or take the remaining time to try to make it better ?
What would you recommend?
Thanks
3
u/Jontii Aug 02 '19
Hi everyone!
I will switch from .net to react soon so I created this simple app that renders top 10 posts from reddit/r/pics. It has limited functionality but I feel like I've created the basics and want to know how to improve. Any suggestions or comments about how to make it better or if I did something wrong would be most welcome.
To summarize, If you have the energy to help me improve my react skills, I would be most thankful.
https://github.com/Jontii/reddit-clone
1
u/badboyzpwns Aug 05 '19
I want to start learning testing. My question is, what should we use for testing? CRA gives us JEST unit testing. But what about end to end testing like Cypress, should we use that too? And lastly, what about enzyme, I've been told it's related to testing components? Should we use all 3?
2
u/NickEmpetvee Aug 04 '19
If you have a popup dialog form (like a materai-ui form dialog) with a cancel and a submit button, what's a good way to keep it open for a second or two if submitted to show a success/failure message and close it instantly on cancel?
The only thing I can think of is to conditionally invoke a sleep message like below. It doesn't feel like a production quality solution though. Thoughts? Thanks in advance
2
u/telllee Aug 06 '19
Hello everyone !!! I am new to react and am trying to create a simple app with react! I saw a lot of videos and decided to get started. I am also trying to use bootstrap with react but am having a lot of trouble and its a bit overwhelming. I'm having trouble getting started and was wondering if anyone here has experience with bootstrap and react could help. Thank You!
2
u/crespo_modesto Aug 07 '19 edited Aug 07 '19
Any idea why when changing state in a functional component with useState/setState, the data changes/component "reruns" from top to bottom, but the html on the client side doesn't change. I don't get it, the values change when I console log them(and they appear in console.log), but the html is the same, no dom flash.
My setState "name" is correct/matches
It seems to be working, all my code reruns from top to bottom when state changes but as I mentioned client side html doesn't change.
edit: from logging everything, my initial state object changes(what I'm passing into useState) but the state from the useState call doesn't change.
edit: I got it, my "setState" which was trying to use a clone of the current state object was not updated right, I was only updating a piece of it(...), but I replaced this with a get object by key type function that generates a new state object and this is working now, still super ugly but yeah
2
u/[deleted] Aug 11 '19
Hi,
I am coming from Vuejs. I recently got a job remotely and I'll be using React. I am taking some courses, but I was wondering if React has in its documentation a best practices guide.
Thanks
2
u/mmyprincesspeach Aug 12 '19
Hello! New to the dev world, so any help would be appreciated! Anyone ever try to render an angular component in a React app?
2
u/argiebrah Aug 12 '19 edited Aug 12 '19
I have been working on a react project locally. I already saw a tutorial on git, but is there any tutorial to save my react project to a github repo? thanks
EDIT: Used this. pretty straight forward https://www.youtube.com/watch?v=ibNqauPoicg
2
u/[deleted] Aug 13 '19
Getting the error - ./src/Table.js
Line 3: Parsing error: Identifier 'Table' has already been declared
Code is
import React, { Component } from 'react'import Table from './TableBody'import Table from './TableHeader'class Table extends Component {render() {return (<table><TableHeader /><TableBody /></table>)}}export default TableSurely I would need to declare Table Body & Header as they are both external components which are being combined in table.js. If am I'm correct.
Can anyone help?
2
u/EvilDavid75 Aug 16 '19
Hi, this is a question on what’s the best recommended way of handling scroll with effect hooks.
I want to freeze and unfreeze a div on demand (freezing hides the div overflow and scrolls it to the current body scroll, unfreezing scrolls the body back to its previous position and frees the overflow of the div). I believe this can be handy when dealing with transitions.
Essentially to freeze the div you would need to read the current window.scrollY, add the frozen class (which sets position: fixed and overflow: hidden) to the div and immediately scroll it to the scroll position you’ve just read.
I tried several implementations, using useEffect, useLayoutEffect, a mix of both or directly manipulating the DOM (ie adding the class manually declaratively).
https://codesandbox.io/s/freezing-dom-6k7lb
The first three implementations sometimes show a flash on Safari, only the last one is flash-free on both Safari desktop and mobile.
I’d be happy to get some thoughts on what’s the best strategy t prevent any flashes, ie adding the frozen class and scrolling the div in the same render cycle.
2
u/cgtyky Aug 20 '19
Hello, I am new to react (but not programming and/or frontend) and I want to learn it. After a quick look in the sub, I noticed a variety of advice about which course I should take. Stephen, Max, Mead, Tyler, Wes etc.
I had to discard Tyler and Wes since they don't have udemy courses. I had to buy the course on udemy because the country where I live has a very volatile currency and it's too hard to cover for expensive course suits. But udemy has its ongoing sales and I can grab it there way cheaper.
I took Mead's Node course previously, and I think he is a good teacher. But he is not using create-react-app and repetitiveness of his teaching style really not good with react. Stephen is not a good teacher in my opinion (it seems Q&A sucks and also keeping dated stuff in the course page so it looks longer? ) and Max is going too superficial (burger app idea is not charming at all, it makes it seem like too basic).
So I looked it up on other courses;
Couldn't find much of a comment, review about them in sub. People seem to suggest Tyler, Wes, Stephen constantly but not much of talk about these guys and courses. So any comment, review about these?
2
u/Irantwomiles Aug 20 '19
What is the purpose of hooks? From what I've read it's just a way to add state to functional components.
2
u/vnlegend Aug 24 '19 edited Aug 24 '19
I'm reading through this code example and I have some questions (https://snack.expo.io/@git/github.com/wcandillon/can-it-be-done-in-react-native:season2/spotify-header)
What does the {...{y, album}} do? The component has props, which contains album (props.album).
For {...{y, album}}, it looks like it's taking variables y and album, putting it into an object, then uses spread operator to pass it to the child as props?
So what does child.props look like? props.album, props.y ? Why do this?
2
u/overcloseness Aug 25 '19
Stupid question warning:
Hooks allow you to use state without having to create a new class.
Why don’t we want to create classes? Is it a performance issue? Because it’s verbose? What is the main driving factor behind rather not just writing a class? It seems like big buzz around something that isn’t that big of a deal. People are saying that they finally use React because of Hooks etc.
2
u/[deleted] Aug 25 '19
Where should i be writing code for styled components?
I've been righting it in the component itself, about the component.
But i've found that it looked terrible having to scroll all the way to the bottom for actual code, so I moved it after the component
2
u/SavingsAssociate Aug 30 '19
Hey all! I have a dumb question. Also I am new to reddit so I sure hope this is going in the right place :D.
Testing. What's the deal?
In my hobby apps, I have started to encounter unexpected behavior. Error messages about setting state on unmounted components, components rendering twice, and so on. So I thought, maybe I should give testing a try. But when I try to read up on it, it seems like its a lot of voodoo and hearsay.
I hear from Mr Kent C Dodds that you should write long tests, that mocking is bad, and the tests should be integration tests. But I don't really know ... how? Like ... whats the syntax. Looking at videos of jest and react-testing-library, it just seems like there are a thousands functions and methods and I don't know what I need.
Help? Does anyone have a good resource on testing React? :)
Thanks!
Tha
1
u/rjray Aug 01 '19
I'm not a beginner in the general sense, but I am to React (and JavaScript has changed so much in the last 3-5 years since I last used it extensively, I feel like a beginner there, too).
When I set up VS Code, I installed a recommended bundle of extensions for Node.js development, including (I think) CodeMetrics. I ended up disabling it because all my React code was lighting up. Now, I'm no stranger to complexity metrics-- I have complexity analysis wired-in to my coding for other languages (Perl, Python, etc.). But with JS, and especially with React, I'm not sure what the cut-off really should be for various parts of a component.
So my question is: do others use complexity metrics on React code, and if so, how small/tight do you try to keep the components?
-Randy
1
u/crespo_modesto Aug 02 '19
This is kind of a "answer whatever you like/suggest something"
This is a vague question but if you have a year of ReactJS experience, what do you think you should know? Redux is optional in this case.
For me currently I can create a CRUD app(with Axios), know most life cycles, but I have not implemented say global state by Context(it seems not much cleaner than Redux from what I've seen regarding how it's called). Aware of hooks but can't name any on the spot.
I also was wondering if there are open projects/things built with ReactJS that would give an idea of how something is structured/architected that is more difficult than a ToDO app of some sort.
1
u/pink_tshirt Aug 02 '19
Getting into this hooks thing.
useEffect(() => {fetchMyAPI(1);document.title = \Button clicked ${count} time(s)`;`}, [count]);Say I want to call my API first and have some other function (eg. a click counter). In this case every time I click the counter up button
fetchMyAPI(1)also gets called. How do I "decouple" these two? Two separate useEffects?1
u/Macaco_BR Aug 02 '19
Hi, im having a problem with states. Basically im passing a state through props and updating a second state on another file receiving this props. Problem is, the second state only updates after the first iteration, making the second state being out of sync with the first one. Its a checkbox for a email, which i mark the checkbox when i want that email and unmark when i dont want, so the state add or remove a string from a array. This driving me crazy and i had to deliver this shit today
1
u/Niesyto Aug 04 '19
Another question in the same thread, but here we go:
I've made a very simple web app that takes some user input and the fetches some data from a public API (wiki and one more). It works, but when you start changing the input, and the output components have to refresh it starts flashing and loading in a really strange way.
Here's the link
If you select the country (Poland works best, this API has some weird data in it), select the parameter you want to get data for, wait for it to load and when it does start changing the parameter, you will see what I mean.
Here's the link to the repository
It's kind of hard for me to give you a code fragment, since I don't know where the problem is. My guess would be
CitiesListorCitiesListElementcomponent, but I have no clue.Also, I would love to see what people think about the code in general. I've just started to learn React, and I don't really know yet what are the do's and dont's
1
u/lottolion Aug 04 '19
I'm wondering how to transition/animate full-screen pictures with text in an article. This site shows what I'm hoping to do: https://www.nytimes.com/interactive/2018/10/26/world/middleeast/saudi-arabia-war-yemen.html. As you scroll down the article, the text makes way for full-screen pictures as captions scroll up, then it goes back to regular text. I'd like to do something similar with charts instead of pics, but essentially the same function. I'm familiar with triggering actions on scroll/percentage scroll, but is there a wrapper or package that lets you do this seamlessly?
I tried posting in /r/learnreactjs but I didn't get a response, sorry if this is an ignorant question.
1
u/Niesyto Aug 06 '19
How to make button group from react-bootstrap not stretch out of the parent on mobile? Shouldn't all things be limited to their parent? Here's a screenshot https://imgur.com/a/YpXDRXn The link to the app (might work well on phones with bigger resolution, as it works well on pc) https://niesyto.netlify.com/ And the code is here in RadioButton https://github.com/Niesyto/cities-pollution
If this question should be asked somewhere else, since it's more about css than react, please tell me.
1
u/NickEmpetvee Aug 07 '19
In some forms I built earlier as React Class components, I used a single `handleChange` method to dealt with all the controlled form fields:
There was a state variable for each form element like
this.state.frmEmail,this.state.frmFirstName,... Additionally, each form element would have the value set to it's corresponding state variable like:I understand that in a functional component with hooks, the
state/<input>syntax will be more concise like this:What I don't understand is how to modify
handleChangeso it can deal with multiple input elements like this because the syntax to set state is different in a functional component. Any ideas?1
u/cmaronchick Aug 07 '19
When do you need to have express running?
It was part of the tutorial I followed originally, and I have my app running on heroku, but I'm wondering if I can just deploy to S3.
1
u/NickEmpetvee Aug 08 '19
Could anyone please explain a real-life example where you'd use the event.persist() method described here? https://reactjs.org/docs/events.html
1
u/billrdio Aug 09 '19
I have a question about program flow when using the
useState()hook and an async function.https://codesandbox.io/s/objective-dream-1wk59
If you click on the console button to look at the console output, why do you see
DEBUG: setDataDEBUG: Running AppDEBUG: after setData()instead ofDEBUG: setDataDEBUG: after setData()DEBUG: Running AppIn other words, it looks like program flow exits the
fetchData()function immediately after callingsetData()and re-renders the component, then the code aftersetData()infetchData()is called.Is that is what is really happening? This is kind of confusing.
1
u/javascript_dev Aug 09 '19
Do you guys still use the chrome debugger with source maps to debug your React apps? If so when would you prefer this to using React Dev Tools?
1
u/somewut_anonymous Aug 09 '19
How limited is Gatsby in regard to dynamic image content?
I am building a sort of personal photo gallery for myself but would eventually like to be able to have multiple users who can upload and organize their photos. I really like the way Gatsby handles images so I wanted to use it but I am confused on whether or not Gatsby can handle users uploading images.
Basically I would have a backend API with all of the CRUD functionality for adding, retrieving photos, etc. from the Firebase Database. Would the entire site have to be rebuilt and redeployed every time an image is uploaded or removed from the database? Or is this something that Gatsby could handle if I used an axios call in componentDidMount to grab the images from the database and load them into the gallery?
I hope my question is clear and thank you for any responses.
1
u/Dfree35 Aug 10 '19
Any advice on how to have the title of a page (the text that shows on the tab on the browser) update dynamically without it saying
undefinedfor a second then updating?Here is an
I am currently using react-helmet but not sure if that is best for it or if it matters. Here is the file where I am currently trying to get it to work with.
I saw somewhere to try to put it in like
componentDidMountbut I am not having luck with anything I have tried or where I put it.Any advice?
1
u/[deleted] Aug 10 '19
whats the different (best approach) for handling the values of input fields?
controlled input's value using onChange vs useRef.current.value to
1
u/jonsherman Aug 10 '19
I'm currently using redux and I was curious if I keep track of the active element in things, such as tabs and drop downs in the redux store. I have to fetch data from the server to populate these items which I use redux for.
1
u/liohsif_nomlas Aug 11 '19
Hi, I notice when i load my project on the local computer and use a login feature in my project to sign-in, then open another tab of my project it already shows as being signed in. This is visible to me as if logged in, an account button replaces the sign-in button. I have a role value setup in this.state.role that gets changed from guest to user when someone logs in. I am thinking the second tab that I opened earlier shows as being logged in because the two tabs are drawing from the same this.state.role..
Is it normal that when you run your project on your local computer that states are shared among multiple tabs of your project that you may open? would this also occur if i deployed my project in say Heroku? Any advice would much appreciated!
1
u/[deleted] Aug 11 '19
Am struggling to get my table to view on my beginner project that I'm working on. Can someone please tell me what is wrong?
Am following this get started guide - https://www.taniarascia.com/getting-started-with-react/
Please see my code:
App.jsimport React, { Component } from 'react'import Table from './Table'class App extends Component {render() {return (<div className="container"><Table /></div>)return (<div className="App"><h1>Hello, React!</h1></div>)}}export default AppINDEX.JS
import React, { Component } from 'react'import Table from './Table'class App extends Component {render() {return (<div className="container"><Table /></div>)return (<div className="container"><Table /></div>)return (<div className="App"><h1>Hello, React!</h1></div>)}}export default App1
u/nobrandheroes Aug 13 '19
Is there a way for the build to compile everything into only an HTML file, on JS file, and one non-minified CSS file?
I'm working on something that is going to be embedded into another page, and not a singe-page application.
1
u/sixfngers04 Aug 16 '19
in redux are there any advantages to using arrow functions for mapStateToProps over traditional functions
const mapStateToProps = state => ( {videoSrc:state.video} );vs
function mapStateToProps(state){return {videoSrc:state.video}}1
u/oktomato2 Aug 16 '19
So I learned React using functional components, hooks and all the new stuff. Do you guys think its worth relearning using class components and lifecycle? Most of the tutorials and code on stackoverflow all use class components which is difficult to understand if you started off with functional component style.
1
u/hurrdurrderp42 Aug 16 '19
Are there any downsides to using arrow functions instead of class methods? I like not having to bind every method.
1
u/Niesyto Aug 17 '19
I've decided to learn the basics of Material-UI, since I've read it's one of the most popular libraries to use with react. However, I've encountered a problem very quickly. I can't set the background color.
const theme = createMuiTheme({palette: {primary: {dark: '#232f34',light:'#4a6572',main:'#344955'},secondary: orange,text: orange,type : 'dark'},})Here's the code for theme. Even the
type: 'dark'doesn't work. I've tried setting the background property in multiple ways, and none of them worked.Links:
Website
Github
1
u/acradmin Aug 17 '19
I'm primarily java backend developer trying to learn react. I have an idea for a component that
Can someone point me in the right direction? I so far see ways to display svgs individually, but I can't quite figure out how to display multiple SVG icons in one big component / canvas.
1
u/yansusanto Aug 17 '19
Hi everyone,
This is my first post here and I hope this is the right platform to ask.
Say I have a gallery and I'd like to implement lightbox using
react lightbox componentThis is my
gallery.jsAnd here's documentation on how to implement it
Pardon my ignorance, my question is how do I implement that into my existing component? Thank you. If someone could point me in the right direction, I'd be very much appreciated.
1
u/ICNRWDII Aug 17 '19
I think I might be missing something really obvious, so this will probably come across as pretty silly.
When you are working on a project how do you back it up? On the last react app I made, I just added the src file to my google drive and an extenal hard drive. Because I use create react, if I'm to back up the whole project it takes ages to copy them over because there are so many files.
Do you just use github to back up? I'm about to upload my first project to github, but do people use it as a way of backing up projects they have just started?
1
u/thatiOSdev Aug 19 '19
So I need help with what course to take for a beginner who learns by building : Mastering React by Mosh or React by Tyler McGinnis.
I thought about React by SuperHi or React for Beginners by Wes Bos both they are both too pricy for me right now.
1
u/[deleted] Aug 19 '19
hi guys , im new to react and when i creat-react-app i cant seem to run the App.js cause it gives me an error like this:
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
i did some googling and some people say its because mine is ES5 but it should be ES6 but i dont know how to change my version of js.
thanks
1
u/workkkkkk Aug 19 '19
I'm using react router (version 5). Is there a simple way to hide a parent route when displaying a nested route? I can't seem to find an example on this by googling for some reason. I feel like I'm using react router incorrectly.
So I would like my last two routes to be nested inside the IndexBody route since you get to those views from that page. I could do some conditional logic about the url path inside IndexBody but I don't like that and would rather just not use nested routes if that's the only way (which is what I'm doing currently).
1
u/Oipotty Aug 19 '19
Hello! Question about redux and selectors. If I need to use a selector across multiple components, the performance of my application slows down significantly. What is the strategy that you would suggest to deal with this so that the selector would only need to be called once?
1
u/javascript_dev Aug 20 '19
Are you guys' react hooks showing their variable names in the new dev tools? Mine are not: https://s.nimbusweb.me/attachment/3217409/xqhphiii8e0psbuqwow6/tkdk21DocwneUctK/Screenshot_2019-08-21_03.08.07.jpg
Copying to clipboard doesn't reveal their names either.
1
u/NickEmpetvee Aug 20 '19
Hi guys. Any thoughts on this? Headscratcher...
https://www.reddit.com/r/reactjs/comments/cstik6/odd_behavior_with_reactjs_app_with_chrome/
1
u/giollaigh Aug 20 '19
I'm a complete beginner with webpack. Basically, I'm currently writing a React/Node app that uses webpack, but it takes almost 2 minutes to start up on Repl.it, which is way too long for a user. I was helped with the config so again I don't know much about webpack, but I'm guessing this is because Repl.it is recompiling the code with every run, which I'm fine with for development, but I'm wondering how production builds work? Do they store the final compiled code and run that so it's quicker? How? Honestly I'm wondering if I should just remove React from my app because webpack feels a bit beyond my current skill level and I don't know of another way to do link React/Node in Repl.it. I can't access my PC much of the day so I kind of need a web host.
TLDR; how is webpack sped up in production? Thanks.
1
u/theReferenceMonitor Aug 21 '19
What is the difference between programmatic navigation and dynamic routing? What is programmatic navigation?
1
u/monir_sh Aug 21 '19
Hey, Just wondering what can i use to persist redux state with react-js? I have been using redux-persist with react-native but I couldnt find anything similar for react-js
1
u/aaronychen Aug 22 '19 edited Aug 22 '19
Could anyone with UI / design experience take a brief look / sanity check on the overall skeleton of my very incomplete portfolio?. It's very empty, but I don't want to get to the point where I'm almost done, and then have to redo / redesign it. The only part done is the sidebar / settings page, and I was largely inspired by this portfolio (though I'm trying to not completely copy it).
Although I'm a frontend React developer for a company, we mainly have a simple flat UI with few fancy animations, so I don't really have much artistic ability or UX training.
1
u/workkkkkk Aug 22 '19 edited Aug 22 '19
Using react-spring, how would I apply a new style/class after an animation is complete? I have a very simple animation of just going from opacity 0 to 1 and vice versa. I need to apply display: 'none' when the opacity is 0 however.
The div fades in perfectly but when isHidden is toggled there is no fade out it just goes away instantly.
Edit: nvm got it, the documentation was very confusing to me at first lol. Still not sure I'm doing it correctly.
1
u/Prof_Petrichor Aug 22 '19
Using react, I'm trying to implement numerical states that are updated when text forms on my website are updated. So far, it's worked just fine.
However, I have one final (Read Only) text input which should be assigned the value of all of the prior fields added together. Instead of my intended result, I'm getting a return value of NaN.
I can't figure out why a State1 = 0 can be incremented by adding 1, but I can't add State1+State2+State3 together to get StateSum. I've got to be doing this wrong! Anyone out there mind showing me how it's done?
1
u/thatiOSdev Aug 23 '19
Has anyone recently taken React for Beginners by Wes Bos? Is it outdated? Is it worth the $100? Should I wait for him to update it?
1
u/Oipotty Aug 23 '19
Hello all,
Question about making get requests using Axios. The reason I'm posting here is because it is within a Redux action (using redux thunk) and I'm unsure if that is the reason why it's not working properly.
The below function is called when my dashboard is loaded and when the value of the datepicker changes. The data loads fine with the initial call with the default date. However, when the date is changed, the correct date gets passed in, but the data isn't updated.
This is me consoling logging one of the promises (response1). As you can see, the url is correct (7/17/2019, the new date I'm passing into the function) but the data is from 7/18/2019 (my default date when the dashboard first loads). I've confirmed that the endpoint is working fine with 7/17 data.
Really appreciate any insight.
1
u/beaver_deceiver Aug 23 '19 edited Aug 26 '19
setStateasync nature causing issues...I've built out a 2048 game and am now trying to make it more dynamic to work on mobile. To do this, I think I need to make my canvas dynamic as well and am trying to use
document.getElementById('board-div').offsetWidthwithin mycomponentDidMount()the canvas.drawBoard is being called with an argument of zero because state hasn't been updated. I feel like this is would be a common issue with a simple solution. What am I missing? Thanks in advance!
1
u/overcloseness Aug 23 '19
When working with Redux, where would someone generally make changes to a value before updating the state.
In the most simple examples (counter example), the value is simply +1 or -1 from the current state and that’s actually just done in the reducer, what about more complicated examples where perhaps your state is an array of objects, and you’d like to update 5 values inside one of those objects.
Would it be correct to assume that you take the original object into a component via mapStateToProps, then change those values inside your actual component, and dispatch your new object via an action to your reducer?
So essentially my question is this “In Redux, is there a right or wrong place to change the new data you send to the store?” I’m not convinced doing it in the reducer is the right spot, but simple examples seem to always do it here because it’s simple
1
u/MisterFawlty Aug 23 '19 edited Aug 23 '19
For Semantic UI layouts, https://github.com/Semantic-Org/Semantic-UI-React/tree/master/docs/src/layouts
is there a way to copy the theming (styling/css) as well?
edit: Ignore me. I knew I had done it in the past. I had just forgotten to import semantic css.
1
u/treddson Aug 23 '19
I'm using the Pixabay API to allow users to search for an image and display the results on the page. Each photo that loads has a corresponding star icon that allows users to favorite the photo. How can I associate or 'bind' the star icon to the photo above it? (screenshot here) When I click on the star I want the url of the photo to be displayed on the sidebar. I can't for the life of me figure out how to accomplish this because it's only returning the entire object. Here is a snippet of code to show you what I have thus far. Yes, I realize I'm only logging to console at the moment, but I just want to get the data first. Any help is greatly appreciated!
1
u/jackylarn Aug 24 '19 edited Aug 24 '19
Hello everyone,
I'm trying to make a simple application that works with redux-sagas en redux-little-router. I'm stuck at the moment with the routing part. If i click to navigate i'm getting an error page which says: Cannot read property 'search' of undefined and i'm getting in my console four times:
Warning: Please use `require("history").PathUtils` instead of `require("history/PathUtils")`. Support for the latter will be removed in the next major release.
This is the application: https://codesandbox.io/s/recursing-rhodes-xmuey OR https://codesandbox.io/live/j225zl
I can't see the error on codesandbox which i weird. Can someone please look at it?
REACT is pretty new for me hope someone can help me out :) Thanks in advance!
1
u/Herrowgayboi Aug 25 '19
If you're building a SPA, for each "page"... Do you build a component and integrate "smaller" components into it, as if it were it's own page, and call it from App.JS file? Or do you create a div with 100% height in the App.JS file and then call the "smaller" components?
1
u/[deleted] Aug 26 '19
Hi, what's the best way of dispatching react-redux actions on component mount? I have a tabbed view with three different tabs. Each one has its own container that needs to fetch data whenever it becomes the active tab. Each tab imports connect from redux and connects props and actions to a child view. I'm just not really sure how to dispatch a fetch whenever the container loads. I could send an action down to the child component and use its ComponentDidMount method but that seems weird to not just fetch the data at the top level since the lower level components will need it.
1
u/[deleted] Aug 26 '19
We're trying to include a ReactJS page into an existing Wordpress installation. Basically a hybrid setup that will pull some data use wpgraphql but the majority of the site will remain the same (non-React).
What's the best way to implement this in terms of folder structure, routing and so on? I've found loads of guides for setting up a headless CMS with Wordpress but nothing for a hybrid/existing WP installation.
1
u/lcrx357 Aug 27 '19 edited Jan 22 '20
Question: the correct way to share and preserve data while switching Routes.
I am working on my pet project in React. Basically the idea is to help folks to learn / get the idea via short hints.
So far I have the following topics: Code snippets, Career advice, JavaScript, UI/UX. If you want to learn more - there is a "Explore at.." link attached to most of the hints. The hints are randomly picked from the DB. You may add them to "My Hints" bucket. The content is currently handpicked from various sources. Basically the same sources I used while learning React when I started writing my app.
The app is written in React + hooks + Material UI. Backend: AWS (Lambda, Dynamo, Gateway API).
Example of a hint (random code snippet):
https://everhint.com/hintlink/codesnippets/javascript/codesnippet/binary-tree/merge/merge-two-binary-trees-full-example-a31bfec9-7500-4501-b1d4-8f7cd9653846.htm
or (random career advice):
https://everhint.com/hintlink/careeradvice/balance/work/life/myth-it`s-actually-about-achieving-balance--c2309ba6-4b45-4279-9299-0c65189881f8.htm
or (random excuse from work:)):
https://everhint.com/hintlink/excuses/excuse/car/flat-tire-f92caafe-d1d0-401d-a24b-a65c52a76d51.htm
Anyhow, I am currently working on a Dashboard component where user will be able to organize hints into custom buckets, create own hints, share, etc.
And here is my question: I am using React Router to create separate routes to Component #1 (where user browses hints) and Component #2 (Dashboard). I do not what to mix in Dashboard with Component #1, since I want Dashboard to be detachable. Both components are sharing JS Map object (where the selected hints are stored). Switching between routes will loose the data, so it should be stored somewhere and not be lost if user closes/re-opens browser window. So far I am thinking: 1. To store in DB on Backend (less preferable, since I do not want to let anonymous users to write into DynamoDB); 2. To store in browser localStorage. What else? Any ideas, comments are greatly appreciated! Thanks!
1
u/imasnyper Aug 28 '19 edited Aug 28 '19
I've got a question about some syntax in a react apollo app. I was reading though this and found this code, and I'm wondering what the ...Component1 ...Component2 syntax means/does. I'm aware of the spread operator, but how is it operating on a functional react component? Specifically, in the context, I expect it to be returning a graphql query field(s).
1
u/Oipotty Aug 28 '19
Hey all - I'm seeing a weird issue connecting my react application to restful endpoints. I'm using axios calls in Redux actions with Redux thunk.
What's odd is that when I do not have devtools open, the api calls pull in old data, or data from the same endpoint but with a different parameter then what it should be pulling in.
This is fixed by opening the Network tab and selecting "Disable cache."
Curious as to if anyone had insight into what is wrong - is it a react related issue, a api endpoint related issue?
1
u/pythophile Aug 28 '19
Hey all, I intend to become a "full-stack developer" and I believe react is the future.I only know HTML + CSS , dabbled with python and just learnt the basics of JS.
My question: What stack would you recommend I learn if I want to mainly build react-native apps and be a full stack developer in that sense, and react apps etc?Thanks in advance =)
1
u/eyememine Aug 29 '19
Ok so I have a button event that passes info, one piece is the event.target.value (in this case "country"). Then I want to filter the array that does not match that info. Basically this is it
onSelect = event => { const value = event.target.value; const id = event.target.id;
};
When the button is clicked it will send the value (country) an and id (France) to the event handler. However I cannot get it to be result.country. How can I accomplish this? I'm essentially trying to do the same this as concating a string with a fetch call ie fetch(
api/${value}).I hope this is clear, my brain is kinda fried at the moment. Thanks for reading
1
u/wallywally11 Aug 30 '19
So I'm learning React and have been really confused about when to use what context characters within JSX. I'm taking the FrontendMasters React Intro, and in it there's code like this:
The ternary isn't the problem for me, but figuring out when to use {} vs () and where they're needed is really difficult for me right now. I feel like I'm missing something obvious, but this is making me feel stupid and really affecting my excitement about learning it. Any tips? How do you all think about when to use what? Are there any thumb rules? WHY is it this way? Thanks!
1
u/WimbashBagel Aug 30 '19
Looking at React, Redux, Express, MongoDB, Socket IO for a realtime web app? Fairly new to the stack but may explore graph ql. Also is hosting on aws or azure a good option for this, how should I approach deployment / hosting? Would hosting the app on these be suitable, and able to deal with the realtime aspect?
1
u/LampShadeHelmet Aug 31 '19
I'm wondering about dynamically moving an object based on the mouse position within its parent. I have an example in JSFiddle of roughly what I'm trying to do, or how I'm imagining it'll go.
Basically I'm looking to move the button as the mouse moves over the button's parent div according to the relative position of the mouse on the div. I've figured out the mouse position on the div, I think, but I can't figure out how I'm to change the position of the button every time the mouse moves.
1
u/FungoGolf Aug 31 '19
Which of these do you recommend for an intermediate React developer?
Fullstack React
Pure React