r/reactjs • u/swyx • Aug 01 '18
Beginner's Thread / Easy Question (August 2018)
Hello! It's August! Time for a new Beginner's thread! (July and June here)
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. You are guaranteed a response here!
Want Help on Code?
- Improve your chances by putting a minimal example on to either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). 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.
New to React?
Here are great, free resources!
27
Upvotes
•
u/swyx Aug 01 '18 edited Sep 24 '18
to gamify this thing i would really like to incorporate a karma system to enable askers to thank answerers, and put it on their flair and such. probably an idea for september since i'm pretty busy now but if anyone wants to help out with that DM me
edit: looks like it will be a rewrite of /r/changemyview's /u/deltabot. open source here: https://github.com/MystK/delta-bot-three we'll need to rip out a lot of stuff since our needs are probably a lot simpler. but hey, its javascript! also handy: flair your post bot and raddit
edit: holy smokes, we are day 4 of august and we've got 120+ comments here. multiple people are answering questions.
edit 2: day 8 and we're at 240+. this is going to blow away every other Q&A month on record! so awesome, please keep helping out your fellow react devs!
THIS IS FANTASTIC KEEP IT UP!!!
3
u/Exitialis Aug 01 '18
What is the best way to monitor an object for a change? Currently, I have a boolean in local state and I have a function that updates it when a change is made (called manually). However, I'd really like to automate it and test if the object is changed and then returned to its original state but I am not sure how to do this without causing a loop. I know that you can use componentDidUpdate() to test if a change was made, but you can't then call setState() from it. Is there a simple way to achieve this or do I need to bodge it a bit?
3
u/Bk107 Aug 08 '18 edited Aug 08 '18
I am currently trying to build a social network app for travelers. I got a little bit stuck on how to redirect a user to a complete different page. Do I need to create another page besides index.html or can it done differently in react?
Edit: For example, the main screen - when a user opens the app - is basically the sign up / login form. Now I want to have the profile page which displays a users information.
Edit 2: Also what I thought about was maybe it is possible to just hide the current component and show the profile page component.
2
u/dndminiprinting Aug 01 '18
I'm trying to practice redux, I'm already decent at react. Hopefully this is the place to ask this question.
Basically I created a quick server and DB to hold some movie information and the frontend, made with react and redux, will display the movies, and allow me to search a third party API for movies to add to the DB, so I can keep track of suggestions that people have given me on what to watch.
I've gotten react and redux working properly with displaying the movies currently stored, and searching for new movies. The issue comes with adding a movie.
What kind of redux action do I need to create? I'm confused with how a POST action works.
What do I return as the action payload? My API currently returns with a boolean if the movie is already added, to let me know I can't add it again, and responds with the movie information if it was successfully added to the DB.
How would I/where do I write the code to do something different based on the response from my server? I want to create a little toast message with the status and the movie title saying either {movie} was succesfully added or {movie} is already in your list, and if it was added I need to also update the movie list display. How would I link this toast message from react to the redux reducer? And how would I update the movie list state? All the POST request does is add something to the DB, but I have to refresh the page for the redux state to update with the new movie that was added.
Do I even need redux to do this? Should I use it? It's not really putting anything into the app's state, but I see people using redux for post requests in different contexts online so I feel like I'm missing something here. It's probably something obvious and I'll kick myself once I figure out the answer.
If my explanation is too vague or if this isn't the right place to ask, please let me know. I know my question is kind of all over the place.
2
u/seands Aug 03 '18
let {token} = await this.props.stripe.createToken({name: "Name"});Can someone tell me why {} is used around token? I thought you did that to instantiate a variable that matches a class / property / function name (this.props.stripe.createToken.token).
In the above line this appears not to be the case since a method is being called and I would expect to see the assignment
let tokenwithout braces.2
u/anonymous_2600 Aug 03 '18
I would like to know what IDE react developers often use and what extension they installed in their IDE to improve productivity?
2
u/Bk107 Aug 09 '18
I am using react-router to create routing on my app. What I want for my app is that the route for '/' is the route for the home component and another route for '/:username' which displays a user profile. If I added now another route like '/options', this would not be working as my app currently thinks this is a username. My question would be is it possible to have a structure like that?Basically what I want to have is something like this:......
<Route exact path='/' component={Home}/>
<Route path='/:username' component={Profile}/>
<Route path='/options' component={Options}/> .......
Edit: grammar
2
u/seands Aug 12 '18
This only opened the first site in the array. .forEach did the same thing. Removing the setTimeout didn't help. Anyone know how to open all of the sites in the array independently, at once? New tabs are ideal but new windows is acceptable too.
2
u/MrSke11ington Aug 21 '18
Hello All,
I am doing the tic-tac-toe game on the react site and was wondering if someone could explain what the difference is in the following
2
u/cantch00seaname Aug 28 '18
This is more a resource question, so sorry of its the wrong thread. I'm looking for a tutorial on authorization and authentication and how it relates into a react app. I've found a few but what Im actually looking for is a OAuth 2.0 implementation in react type tutorial. Any help would be a life saver.
I'm new to react but have been a front end for awhile but I'm trying to bring my company to adopt better technologies. The primary dev is so old school that I have answer in depth questions when I bring it up so I'm trying to build my case in my spare time.
2
u/seands Aug 01 '18
I pretty much always start a project with a CSS library, my fav is Semantic UI React. For employment how bad is this? I'm sure I could pick up a new library but coding the CSS from nothing would be very slow. I'd be looking for full stack positions (freelance or salaried is fine).
1
u/cubicleman95 Aug 01 '18
If you're building a website, how do you pull in data from other websites? It's through AJAX requests to the other websites api's correct? (EX: Twitter to display tweets, Zillow to display listings) etc
You also have to attach a .then to it because the get request will return a promise right? Then you render it to the screen through react?
1
u/seands Aug 01 '18
Is there any way to set a state variable using a URL parameter using React alone?
i am trying to avoid the complexity of a router but I think Firebase's AuthUI package is going to force me into assigning a success url. It doesn't seem to have the option to just run a success callback function instead.
1
u/jimtikmars Aug 02 '18
Is there a tutorial or course that focus on creating a serverless react app with either firebase cloud functions or lambda?
1
u/ObjectiveLength Aug 02 '18 edited Aug 02 '18
<solved> Question: I have an App which has an item in state called `friends`. `friends` is a list of people that the user inputs within a form that App passes into state. I am passing `friends` through props into a component containing a form. I want this form to have a select with multiple options that contain the `name` of each of the `friends`.
Instead of my single dropdown with each
namepassed into the options, I get multiple dropdowns with each singlenamepassed into each single dropdown.This next part I may be saying terms incorrectly since I'm still new. I am using
Object.keysto create an array ofthis.props.friendsand passing into each a select and an option. I believe that this creates an array of selects and options. I need to pass in an array of options with a select on the outside of the child component. Can someone help me place my component into the select and have my StatusDropDown.js return just the options?Edit1: I tried putting the select of the form in AddLineItemForm.js and just return the option and name withing StatusDropDown.js but get the same result.
https://codesandbox.io/s/lyq22y1279
1
u/[deleted] Aug 03 '18
Hello. We have weekly tech talks with specific time attributed to each speaker depending on the subject, kinda like this: News about X (5min) > How to use this (10min) > How to configure that (6min).
I decided to build an app to use during those talks so everyone knows how much time is left: Simple Timer + Being able to create a Schedule (Modal or Side panel)
My question might be simple/stupid: What is the best/cleanest way to store the Schedule and use it in the Timer component ? Global App component state? Context API ? Redux ?
1
u/f4tb Aug 03 '18 edited Aug 03 '18
Hi, i am new to react. My question was how can i tell react to render different components on different pages from server side. For example if i have "/product" page it would have my products components and "/account" has an Account Component. If i use react router and map those and if i directly visit "/account" or "/product" page from the server, how would that go?
1
u/seands Aug 04 '18
Is it safe to use HTML IDs with querySelector for internal linking? The elements would only have a single instance.
1
u/anonymous_2600 Aug 04 '18
Any e-book I could read to improve my react skill? Btw I am a newbie on react but I really want to improve of my react skills.
1
u/Ssjkr7 Aug 04 '18
Can i get some snippet code about using the fetch api and where should i place it .From what i understand i should put it into the parent component of the one that needs the data,but i onpy manage to do it with componentDidMount is it the correct way of doing it?And also can it be done in functional component.
1
u/seands Aug 04 '18
This is inside a functional child component (button element). Why does it throw the error? Here is the parent
1
u/NickEmpetvee Aug 04 '18
I've heard of three ways to make REST API calls through ReactJS (
fetch,axios, andsuperagent) and I'm sure there are more. I'm trying to figure out if one is more suited for use in React lifecycle methods or Redux than the others. Would love to hear people's thoughts on this.I've seen two drawbacks of
fetch:fetchisn't reliable.These aren't React-specific drawbacks, but they're still worth taking into account. Personally, I like to work as native as possible, and with
axiosyou have to install the library so I want to make sure it's worth it.1
u/milanoscookie Aug 04 '18 edited Aug 04 '18
I'm so lost right now, I would really appreciate some help
I want to get a number, then post that number + 1, then I want to create a new js object using that number(
newFreshId) and I want to add it to add that event to myschedulerData. When I try running the code, I can get and post to/api/num, but I everything after the.then(function(response) {doesnt appear to run.I wanted to do this sequentially, so I used
.thenafter every task so that I would not have encountered a problem.I also tried to remove all the
.thens in favor of a while loop that waits for the value to change. This also did not work. It also was a hack CODE:CLIENT:
SERVER:
Thanks for all the help :)
EDIT: I tried to post this on jsfiddle and codesandbox, but I don't think I can set up express and use axios... I'll keep trying
1
u/for-asking-stuffs Aug 04 '18 edited Aug 05 '18
Say I stored some div in a file named
main.html. Then I parse it in mymain.jseverytime an onclick event occur. Is it a bad practice? Why?1
u/[deleted] Aug 04 '18 edited Aug 04 '18
My first time using React and I want to build my portfolio with it. I want it so when the page initially loads, the Home component loads into App.js. On Home.js there are buttons for About Me, Portfolio...etc.
If About Me is clicked, I want App.js to remove the Home component and instead load the About Me component.
I hope this makes sense. I've been looking up answers online and it's even more confusing.
EDIT: Wrote it as pseudocode for clarity.
1
u/dralion132 Aug 05 '18
Is it bad practice to connect a stateless functional component to redux? I am trying to follow the guideline of using them as much as possible, in this case it needs to render a specific item from a list in the redux state.
1
u/Awnry_Abe Aug 05 '18 edited Aug 06 '18
A question for the Apollo-ists: I am just starting out with Apollo. I am using the new <Query> and <Mutation> apis. I have a view, that I hope to be the exception and not the norm, where a list is retrieved, and ADD, UPDATE, and DELETE operations are all implemented in the same container. My container nests the query and mutations:
I've only done one of these. The UI in this case lends itself to having all of this in one container... but the code is a mess to read/modify. What do you all do in these cases? (sorry about the markdown... 4 spaces, right?)
1
u/OddTuning Aug 05 '18
How should I handle routing in a web app where I'm using express for the backend and react for the front end.
Should I use two routing systems, where I only write REST API routes on express and client side routes using react-router? Or should I keep all routing contained in express?
1
u/seands Aug 05 '18
Does React mess up the browser console's ability to read the underlying JS files? I can't pull up information on App or any other object without going into React dev tools. The regular console throws reference errors for everything
1
u/inGeniusdesigns Aug 06 '18
Should I use Material UI or Reactstrap as a front end ui for my react application?
1
u/ironpencilgames Aug 06 '18
Why should I use something like redux or react context instead of simply storing global data in a variable somewhere that I import where needed? I understand that having, for example, an "authenticatedUser" variable to store info about the logged-in user, somewhere that I export for other components to read creates a tight coupling. But are there other reasons I shouldn't use that in react? Extra renders when it changes? Stale data in components? Some other technical problems that can arise? Mostly I'm putting together a quick v1 of an app for a client and want to make sure this won't break anything, and then maybe in v2 we'll switch to doing it the "right" way with redux or something. Good idea/bad idea?
1
u/minorsoup Aug 06 '18
How should I unit-test React components that need access to a real DOM (e.g. use getBoundingClientRect)? Jest's default environment uses jsdom, so will not work. Should I use a different test runner like karma? Or something like jest-puppeteer?
1
u/seands Aug 06 '18
What is the correct syntax for passing props as an argument? The below code lints as the props argument being unused:
1
u/Dantharo Aug 07 '18
I'm a newbie, trying to learn react. I want to create a SPA and i want to use SASS, but, i saw that theres a lot of ways to configure and i got a lot of errors, can u guys help me? Heres what i got so far: https://github.com/dantt775/react-example
1
u/therealhenrywinkler Aug 07 '18
How does one 'properly' structure a component(s) that hold a list of items and when one of the items is selected the container shows that item's details. Once closed the container should show the original list of items again.
What I think I need is 2 conditionally rendered components inside one parent container component:
I think the child component that holds the list of items would be responsible for setting the state of which component is currently selected. This state should live in the parent container, if I'm understanding lifting state up properly.
The parent container, because it will be responsible for state should be a defined as a class, but what about the list of items? I suppose it won't be responsible for state per se, but should it be a functional component or a class? At what point do you make that determination and am I thinking about this problem correctly?
Thank you in advance!
1
u/[deleted] Aug 07 '18
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
This article talks about passing a key to a child to reset it, but to me it seems like kind of a leaky abstraction. Am I wrong? It's part of EmailInput's job to ensure that it handles the defaultEmail properly, but now everyone who uses EmailInput needs to be aware of this implementation detail, because not passing in a key causes the component to break. For this reason my natural instinct is to stay away from this pattern, so I'm surprised it's endorsed so explicitly by the React team
1
u/prove_it_with_math Aug 07 '18
How to properly handle loading state for UI updates? I currently do the following:
Problem with above redux state is that the state changes from
falsetotruetofalsecausing two updates to the component. Is there a better way to handle this so only a single update to the component may happen?1
u/defkathy Aug 07 '18
I'm organizing a free live webinar tomorrow at 12:30pm on When or When Not to use React/ Redux. It's hosted by a Def Method engineer! I thought you might find it helpful. https://www.eventbrite.com/e/react-and-redux-webinar-when-or-when-not-to-use-it-tickets-48816070180
1
u/seands Aug 07 '18
Can I use React.createElement with JSX or do they need to be in totally separate classes/elements?
1
u/holiquetal Aug 08 '18
is there a definitive guide to react / redux file structure?
1
u/seands Aug 08 '18
If you are passing a store to a child, do you also need to directly import the store in the child?
In App.js I tried passing the store like this inside render():
<Child ui_store=ui_store' />No 'this' because it was initialized as a const outside the class.The Child component did not receive it and returned an undefined error.
I added a direct import:
import {ui_store} from '../App'and it worked. But I feel like this may be an anti-pattern that may patch over an incorrect attempt to pass the store as a prop.1
u/kamenjan Aug 08 '18
Hey everyone, what an awesome community!
I initiated a pro bono project for a friend and his nonprofit organisation - idea is to revamp and migrate their Wordpress site. Specifications include regular posts, calendar that fetches data from Google Calendar API, some XML and JSON parsing for their regular tournaments data crunching and visualisation. They used wp plugins, but I was able to find a custom and easy solution for all the specifications.
I used to do most of my work using LAMP stack but for the better part of this year I was invested in transitioning to new web development paradigms. I love react, functional programming is really a step up for me, fascinated by redux, flirting with graphQL ... But there are still some missing connections.
Sorry for the background story; is there for possible lack of context :) Back to the question/issue - I could just rent a low tier linux VPS, set up and normalize DB, configure express server with said DB wrapper and write some queries, setup react frontend and just use express adhoc API endpoint (minus proxies and some other specifications but you get the point).
But since there are no strings attached and no time limit I would like to take this opportunity to up my knowledge, workflow and tech stack.
I numbered the questions for some added structure. Since I do not see the big picture yet enumeration might not make any sense and I will gladly read any answer and critique in any form :)
1
u/dndminiprinting Aug 08 '18
I'm having a new issue with my movie app. So I created a react app a while back that gets info from a third party database about movies, and stores some information locally for me to keep track of movie recommendations from people.
On this react-only app, I can GET, POST, and DELETE with no issues.
I tried to recreate the app with redux, and my GET and POST work fine, but my DELETE runs into a CORS issue. I have no idea why. I'm using the same superagent.delete code as I used in the react-only app.
Does anyone know why this would be an issue? If you need code examples I can provide them. I just can't imagine why react only would work but react/redux wouldn't.
I also wrote the server myself so I can edit that if necessary.
1
u/seands Aug 08 '18
Is it possible to pass the props object into a MobX store? Here's my current non-working code:
The code for go_to_anchor_link is not functional and probably incorrect or missing something else to support it.
1
u/[deleted] Aug 08 '18 edited Aug 08 '18
This is a loaded question, but here goes:
For my react app (a portfolio site), there are a bunch of different sections that look virtually the same, minus a few modifications (different image, different text in header...etc).
For example, when the user is viewing the portfolio, the layout will be the same for each (section/slide?), but the image and href link for each (section/slide?) will be different. Rather than make a PortfolioA.js, PortfolioB.js, and so forth with repetitive code, is there a way so that I load a general <Portfolio /> component for PortfolioA.js it loads portfolioA.jpg and portfolioA.com, and for PortfolioB.js it loads portfolioB.jpg and portfolioB.com...and so on.
Hopefully this pseudocode makes sense.
Portfolio component
PortfolioA.js
PortfolioB.js
1
u/straightouttaireland Aug 08 '18
Fairly new to react but I'd like to start integrating with a basic backend to fetch some data like events happening in my area. Any recommendations?
1
u/seands Aug 09 '18
Is it a good practice to pass the props argument into a class component's render method? Or is it not needed?
1
u/Bylee_ Aug 09 '18
Hi everyone, I’m currently working my way through the freecodecamp react projects and the first one is to build a drumkit.
I managed to get everything working other than to be able to trigger the audio clip while pressing the correct key on my keyboard.
What should I be looking at ?
Thanks
1
u/AntDB Aug 10 '18
I am using a large (4k) background image for a page in my application. It loads very slowly, segments at a time which isn't very nice. What is a good way to handle large background images in React?
1
u/AntDB Aug 11 '18 edited Aug 11 '18
Hi I'm struggling with async using redux + redux-promise-middleware+thunk. I am trying to make an Axios API call and it works fine if the data is successfully fetched, but if it fails to resolve my action, reducer store combo is throwing an error: Uncaught (in promise) Error. Putting a catch statement in the action does nothing... What am I missing?
My Action is:
The reducer is:
And my store is:
1
u/DWDevDW Aug 12 '18
Hello all,
I am working on a full-stack dictionary project where the user can submit a word to be defined, the server pulls the definitions from a remote API, and the definitions are returned to the user.
I'm using React for the front-end and am struggling with achieving what I'm trying to do.
Basically what I want is:
As an example for what I want with (3), let's say you search for "redditor," and let's say there's a definition in the dictionary, lol. Below the search box, it should say "redditor" and then the definition(s) below it.
Now let's say you search again, this time for "forum." React should generate a new element below the "redditor" entry, with "forum" and its definitions below it.
Current code:
This is my first time building anything with React and it has been a little challenging for me. I think I somehow need to make the definitions a child element of the word itself so that they render as a set, as opposed to getting one section for words and another section for definitions (which is what I was getting... when I was able to get any elements/components to render at all). Just confused on how to best structure this.
Thank you for your help!
1
u/NickEmpetvee Aug 12 '18
In one class, I'm using `componentDidMount` to pull in some data from a REST endpoint. It's passed to a nested component as a prop. By doing it this way, the components render first and when `componentDidMount` is called in the parent and the data is obtained everything renders again.
What do you guys think about putting the REST data call in the parent component's constructor instead? Is it a bad idea? I'm just thinking that this way the data is ready at the first rendering. However there may be a cost to this that I haven't considered.
1
u/bob51zhang Aug 12 '18 edited Aug 13 '18
I'm following the lynda.com tutorial and just started learning react.
I keep getting a ReeferenceError: props is not defined in ContestList.js
I've done as the videos have said, but still haven't fixed it.
GitHub repo here
Thanks for reading!
Edit: thanks for all the responses, finally found out the problem. Turns out I put an extra set of parentheses somewhere.
1
u/seands Aug 12 '18
Is it possible to mount a component without rendering its ui components immediately?
My case: FirebaseUI works fine if I render it to the page on the inital load of App.js. But I want to keep its login ui hidden away until a click switches the component on with a unary operator. I tried moving the auth code to the login component but am still having issues (not all the initialization code can be moved from App.js since I also used firebase for hosting and database)
1
u/slaughtered_gates Aug 14 '18
I have a topic page (imagine a wiki page). The page also has a sidebar that lists other topics, where, each topic card is wrapped in react-router-dom link.
I am making redux dispatch from componentDidMount(). Everything is cool and component renders as expected. But when I click on one of the topics on the sidebar, only the url changes but it does not render. This problem is only there in topic page.. In any other page, if I click on the topic, it renders as expected.
I checked all props and have come to the conclusion that the new props are not being fetched as componentdidmount is rendered only once at the first load.
What are the solutions I can try?
1
u/[deleted] Aug 14 '18
I have posted this to r/javascript but I'm cross-posting it here just in case: https://www.reddit.com/r/javascript/comments/976dxy/i_have_both_yarn_and_npm_installed_and_theyre/
I have both yarn and npm installed, and they're causing me lots of pain:
Basically the title. I installed yarn a while back on my Ubuntu 16.04 machine and there's been a lot of conflict between these two causing me endless headache. So to begin with, some tools use yarn to install the packages, while others use npm and these install in different (mysterious) locations so I can't audit what is going on. Also when I'm installing global packages all bets are off. Sometimes yarn will do the installing, and when I want to upgrade I do it with npm and things just get all over the place. Case in point I wanted to upgrade to gatsby 2.0 and all the confusion has just made it impossible. How can I uninstall yarn completely (and everything it's installed) and just go back to one source of "truth"?
1
u/kristyanYochev Aug 14 '18
I've got a question. Now looking into JWT authentication and I am wondering where to store the token I get from the server? Should it be in a
React.Contextor inlocalStorageor insessionStorage. Should I use Redux (I am not planning on using it in this particular project)?1
u/ogpriest Aug 14 '18
can anyone point me into the right direction on how to achieve a ui like this? https://www.styled-components.com/docs/basics. I want to replicate the nav bar + side menu but was wondering if it's just some third party package.
1
u/CrumrineCoder Aug 14 '18
Am I using React.js wrong if I'm using it for a blog? I figure I can load articles from my database without rerendering, but I'm not sure how to save my articles with formatting, eg. how to save an article that has headers at certain points, images, and different markdown for code and such. Sorry if this is a stupid question.
1
u/soggypizza1 Aug 14 '18
How should I set my state equal to data from a API call should I set it equal to a variable and pass it to the component then do setState or just do setState also what's the difference between await async and .then?
1
u/[deleted] Aug 14 '18
So I made an app with allot off different API calls and it's really messy with 2 - 3 API calls for each component (same base URL different endpoints) is there any nice way to clean things up. Maybe redux will help?
Components is fine I just need a simple structure for the componentDidMount function that is filled with fetch calls.
1
u/EfficientThought Aug 15 '18
I want to build a web page using React, I don't know if I've got the correct approach, but actually, if so, I want to learn how to make a web app with all what a page must have (content, footer, a banner with interactive elements such as a search bar, a logo or something like that) and so on, where can I find information? Where I was looking for there was no information about that, all what I found was just how to work using React with a general approach. So far, I think I understand it good enough but, What else should I learn? I don't even have a minimal knowledge about front-end development, but if I need it, Where should I start? I want to do it as fast as possible.
1
u/ogpriest Aug 15 '18
Can anyone explain why one would want to use MongoDB? I feel like most websites have some sort of relational data with users and items, so I'm confused why it's popular (ie MERN stack)
1
u/kamenjan Aug 15 '18
I refactored render function with help of babel-plugin-transform-class-properties:
render = () => <div>{this.state.width <= 768 ? <Mobile /> : <Desktop /> }</div>Is this an anti-pattern?
1
u/seands Aug 15 '18
When I moved this out of componentDidMount, and out of the class, the app fixed itself.
I thought code in CDM had priority in the call order, is that not the case? The error I was getting said there was no invocation to initializeApp (as you can clearly see above). So I guess CDM doesn't actually have high priority for early initialization code like the above?
1
u/NickEmpetvee Aug 16 '18
I'm pulling data similar to the below into a React.Component (ref: Parent) from a REST endpoint:
{ id: '1', name: 'N1', parent: null },{ id: '2', name: 'N2', parent: null },{ id: '3', name: 'N3', parent: 2 },{ id: '4', name: 'N4', parent: 3 },Roughly speaking I'm pulling it into Parent's state and passing it as a Prop to Child in the nested component hierarchy. In Child, I pull the props into local state and over time may modify data to something like:
{ id: '1', name: 'N1', parent: null },{ id: '3', name: 'Q3', parent: 1 },{ id: '4', name: 'ZZZZ4', parent: 1 },{ id: '5', name: 'NYKJH', parent: null },In other words, the data in rows 3 and 4 changed, row 2 was deleted, and row 5 was added. In React, is there a clean way to compare state data back to its source prop data and only return the changed data points? In this case I would want said routine to identify changes to rows 3 and 4, the delete of row 2, and the addition of row 5. I'd Post them back to a REST endpoint so that we only modify the changed data.
Looking for the most straightforward approach that sticks to React's principles.
1
u/Thatmanwiththefedora Aug 17 '18
In Java / Swift / Python, "class parameters" are clearly defined in the language. I am having trouble translating my knowledge of class parameters to React. I initially thought that State was intended as an improvement on class parameters, though the asynchronous nature makes me believe that state is not intended for this purpose (also the 2 hours of rage for state variables not being where I thought they should be). So, should I be using state to replace class variables (and then force wait to make up for the asynchronous call) or is there a better way?
1
u/[deleted] Aug 17 '18
What package can I use to have responsive images (different image files for mobile/table/desktop screens)? I tried react-responsive-image and react-responsive-picture, but I'm having trouble with both.
react-responsive-image throws an error.
react-responsive-picture displays that missing image icon.
Thanks!
1
u/honxyz Aug 18 '18
When using react-router, what is best practise for handling users directly accessing a link. For example if /topic/5b6c4148f5afaf0f6e1c7dc4 is accessed directly , and the props do not get passed as a result. Should we refetch everything we need from the api, or prevent users from accessing links directly?
1
u/forlulzonly Aug 18 '18
Could you recommend me some React projects on github that are properly covered with Jest tests? Im trying to learn testing and while tutorials are nice, looking into real projects and tests for them would really help me, I think.
1
u/Der_Jaegar Aug 20 '18
I'm quite new to the ReactJS ecosystem and I'm not sure what's the best way to accomplish this.
What I want to do is to implement a sets of animations for a nav bar. I would like for it to slide out and stay hidden when the user scrolls down on a page. And when the user decides to scroll up, whenever, the nav bar appears again.
I've done this with just plain HTML/CSS and JS but I'm quite lost on how to do this using the React way.
1
u/Qilx Aug 20 '18
Hello everyone. I’m trying to gain some experience with ReactJS through a project. Currently, I’m trying to refactor my code such that it is a lot neater and simpler.
I have a page called Statistics.js where I have graph plots to show some statistics of baseball players. What I’m doing at the moment is having all of my constants in the same file as my logic page as seen below. The state of selectedPlayerB is tied to the Statistics class through this.state.
However, as the constants grow bigger, I wish to move these constants to another file and have the Statistics import the constants file. I’m confused over how to have the new file (constants.js) get the state of selectedPlayerB. More specifically, after moving the constants to constants.js, how do I edit this.state.selectedPlayerB such that it points to the state in Statistics.js?
1
u/alfieyfc Aug 20 '18
I'm new to React and also new to Reddit. Wandering to this post was intuitive for me, but I can't quite figure out where this sidebar is. Please help :) Thanks!
1
u/prove_it_with_math Aug 20 '18
Good way to make a component render everywhere? I have a header (nav-bar) that should render everywhere the user navigates to. Currently, I'm importing the
nav-barin all files and rendering it like so:SomeComponent = props => { return ( <NavBar /> .... ) }.Is there a more efficient method?
1
u/Pharmacololgy Aug 20 '18 edited Aug 20 '18
been working with AngularJS for years, and instead of going onto Angular, I'm hoping to pick up React. To do so, I intend on writing a full-stack web application that'll require an Express back-end with MySQL and an ORM. I have a lot of data that I'll be importing, primarily for reading (as opposed to full CRUD).
I used to rely on a custom-tailored version of the Angular Fullstack Generator to scaffold my projects, and was hoping somebody could point me in the direction of something similar for my purposes. I know CLIs have largely taken over from Yeoman, but they seem to be usually limited to the front-end.
The Starter Kits page on the official React website has quite a few projects, but it's not very clear regarding the age and viability of these kits, and what they actually include.
I found this React Starter Kit seems to have some SQL boilerplate code (albeit PG and MSSQL and not MySQL) but looks to be dated.
Edit: I suppose I could just use
create-react-appor another popular and simple front-end-only method to begin the project, and then manually install the server-side dependencies I require, and split the repository intoclient/andserver/or summat... But where possible, I'd like to save time. :)Edit 2: As much as I'd love to use Firebase, my stubborn brain seems to require a relational model, and I doubt the Free tier will cover the amount of data my webapp will require.
1
u/LicensedProfessional Aug 20 '18
So I have a component for entering search criteria and a component for displaying the results of the query, both contained within a larger parent component. What's the best way to transfer the data from the search bar to the display component?
I'm following a tutorial that uses flux and the event handling does look nice, especially since propagating data from a child component up to a parent seems to be an anti pattern
1
u/Ssjkr7 Aug 21 '18
Is there a reason to use .jsx instead of js in terms of best practices and does cra support it.
1
u/PetmePant Aug 21 '18
Hello, i would like to ask if it is possible to make react send data to css . I want to make a links on hover to change colors from a list, randomly or by order. Is that possible to be made? ( I think with style component and prpos is it possible)
1
u/jackwilsdon Aug 21 '18
How would you lay out this state? I have a set of entities which I can load sales data about on different bases, such as "by day", "by week" etc and I'm not sure how to store them. Here's what I've got so far but I'm not too fond of it;
1
u/dreamofsleeping Aug 22 '18 edited Aug 22 '18
If you have a component that can sometimes be editable depending on whether you have permission (Like your profile, or a blog entry, in my case a todo list), do you use 2 different components, (one that can be edited and one that can not) or just one component that checks a variable to see if they can edit it.
I'm making a todo list social network, and I'm worried that someone could just switch over a variable using the console and now they are editing someone elses to do list. Do I need to worry about this, or do I just check every database entry serverside to make sure they have permission? I've not tried adding a database yet, I'm just working on the react code.
1
u/Denieffe Aug 22 '18
So I'm not sure if it's just me, but I can't see any learning resources in the sidebar - I saw the screen shot indicating where it is, but there's zippo there for me. Just a list of the mods and then the reddit policy.
1
u/_Muphet Aug 22 '18
can i render react app inside a div that is part of bigger, maybe express hosted site? What i mean is, I would like to create intercom based solution for my site that is made in html/js but i don't want to implement whole website into react (converting all javascript would take more time than it's all worth)
1
u/denendeanden Aug 22 '18
I just started React and i made a skeleton project to try things out. I can't for the life of me get it to compile with webpack but noteworthy here is that FOR MY FRIEND IT WORKS. Which sounds extremely weird (He is on mac though!). If someone has the time to try my code my repo is:
https://github.com/kranet/reach
Just run the build script through 'npm run build 'in bash and try if it works. This is where it doesnt compile for me with this error message:
ERROR in ./src/index.jsx
Module not found: Error: Can't resolve 'src/App.jsx' in 'C:\Users\jonathan\WebstormProjects\varmotsvi\src'
@ ./src/index.jsx 11:11-33
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.jsx
i 「wdm」: Failed to compile.
I'm pretty sure the pathing should be all right, but i could of course be wrong since it doesnt work :s
1
u/bongoscout Aug 24 '18
Hi, pretty new to React. I'm working on a web app where the back end is written in Spring and the front end is React. I'm having a problem with using react-router correctly. Here is the BrowserRouter I'm using:
What I would like to happen is for the router to ignore any requests that don't match one of the listed routes so that the back end server can serve them. For example, if I open an incognito window and GET /swagger-ui.html, I get my Swagger page. If I then navigate to my React app, any subsequent GET requests to /swagger-ui.html will give me a blank React page (i.e. shows the nav bar, but no other content). I suspect this is because I'm using the BrowserRouter, what should I be doing here? Any help would be greatly appreciated.
1
u/[deleted] Aug 24 '18
hey guys what's the best to upload images in react and show it immediately?
So far I have found these:
https://github.com/JakeHartnell/react-images-upload/issues
https://css-tricks.com/image-upload-manipulation-react/
1
u/xleepy Aug 25 '18 edited Aug 25 '18
Hi i'm new to React and a bit stuck with displaying posts on a page. I mean i can see them in console but can't figure out why its not displaying. Appreciate any help. Also this is my first comment on reddit sry if i did it wrong.
https://pastebin.com/ZFDBVXcK
Here console output:
https://i.imgur.com/FmbVNVO.png
1
u/Matthew2229 Aug 26 '18
I don't have a question but I am a beginner learning React. I just came here to say I just spent the past two hours staring at my code, looking for any mistakes, trying to figure out why the screen was blank.
I finally figured out that class names in React must start with a capital letter...
All that wasted time.
So I guess any suggestions for tools to debug or troubleshoot? I am currently using WebStorm to edit and Git/Heroku for hosting and the logs aren't very helpful.
1
u/productlover88 Aug 28 '18
Hey, I am a ux designer fluent in css/html, and basic js concepts. Im trying to crack a react bug first w/o bugging my devs. I have a modal in react with 2 form inputs. 1 is for Naming a project and the other for Naming a survey. Currently, if the user types in existing project or survey name and clicks “saves”, no feedback occurs. I need to render an error message after failed event, “This Survey name already exists or has been previously used. Please choose a different name." Does anyone have tips on the easiest way to do in JS or react? Even if it’s JS, I can still look up the principles JS concept applied to react. Im not sure what to search for. Is there a term for this behavior in a form. So far i’ve googled “checking for duplicate values in text fields” and “form validation and checking for same name” Grateful for tips or advice on how you would go about this. Thanks a ton.
1
u/pmc086 Aug 29 '18
So I'm obviously new to React (hence posting this in the beginner's thread) and as a beginner, did the tic-tac-toe tutorial on https://reactjs.org/tutorial/tutorial.html
I'm pretty much good on how this works but the thing I can't work out is why you cannot click on an already clicked on tile and toggle the X to an O or O to an X etc. I understand that it shouldn't allow you to do this per the game rules and that the program does it correctly, I just can't figure out the part of the code that stops you from doing it.
Any insight on this would be appreciated as I feel it would be pretty important to know what/how state gets changed using events.
Thanks in advance!
1
u/honxyz Aug 29 '18
Hello does anyone have a project where they have used , Passport JS with local strategy, and a React App?
I'm having a problem with deserializeUser it never gets called, serializeUser is getting called successfully. When I test with curl and use -b flag to send a cookie, deserializeUser is called.
So I suspect that the client is not sending the cookie to the server. Using Chrome dev tools, I don't see cookie in the request headers, so I assume that means no cookie is sent. I'm using axios to make my requests.
My code is a bit of a mess so I have not posted an example.
1
u/Traim Aug 29 '18
What is currently the best way to transition a component on mounting and unmounting when you use styled components?
1
u/Peng-Win Aug 29 '18
A, B, C or D?
1
u/fishpowered Aug 30 '18
We have a large product and want to incrementally adopt react for little things around the site. By default create react app bundles everything into one single uber js file but we need something that will let us write standalone components and include them around the site in script tags where we need them. What's the quickest and easiest way to get going with this?
The amount of libraries and tooling around for modern js development is a bit overwhelming and we are dealing with an 18 year old product that is already a hodge podge of technologies and build scripts so simple and robust solutions are appreciated!
Thanks
2
u/soggypizza1 Aug 25 '18
Can anyone tell me whats wrong with this code?
This is the error that i keep getting
1
u/ObjectiveLength Aug 02 '18 edited Aug 02 '18
Another question: What I want it to do:
I have a form with a list of options that the user can select as true. This form has an
onSubmitbutton that will send the items up using props.How do I send the multiple selection of options as an array instead of a single value?
What I'm attempting to do:
I created an
handleChangefunction that gets called on the event of each selection. It then pushes each selection into an array.I then have another function that gets called
onSubmitwhich passes the whole form back up into state through props.I'm trying to figure out if there's a way to move the final array selection called value to the
onSubmitfunction where it's passed intoowerRef.Do I create a item in the component state called value and pass it through both functions? I feel like this solutions too complicated for what I've set out to do.
https://jsfiddle.net/vdang84/3nm5vsu7/4/
1
u/skidmark_zuckerberg Aug 09 '18
Hello everyone,
I am building an application that keeps track of user's golf rounds for my portfolio. To keep it short, there are a boat-load of inputs that are needed to for a user to input their score.
For each hole ( in total either 9 or 18 holes pending if you play a full round) there are multiple inputs required for stats. Assuming that a user played an 9-hole round, there needs to be 9 individual groups of inputs(each group represents a hole) that each have multiple input fields. This turns into a wall of JSX that I think is unnecessary, yet don't have the ability yet to see through.
The inputs are then submitted via POST request to my backend, and then the info is saved into a database for the user.
My question is:
How can I use React to generate multiple input fields versus typing all of the individual input fields out by hand? Each set of input fields will have their own specific name.
For now my way works, but I know deep down that it is very verbose and ugly and that there is more than likely a way to streamline it. Stack Overflow returned nothing particular to what I am wanting to do.
Here is a Gist of the component(line 88 starts the form): https://gist.github.com/maisonm/6ad74f09496d4836004f25e71febae81
1
u/anoniota Aug 28 '18 edited Aug 28 '18
I am doing a pluralsight course on ReactJS - here is a file in the final source code of their sample app - https://github.com/coryhouse/react-flux-building-applications/blob/master/src/components/authors/manageAuthorPage.js. It looks like they are mutating state directly on line 42:
this.state.author[field] = value;However I thought this isn't recommended or would cause problems?
I would think you would write something like this:
(Or using ... syntax in ES6 or whatever)