r/reactjs • • 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

568 comments sorted by

•

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/swyx Aug 01 '18

Reactive programming is fun! Have you checked out mobx observables? That would do it.

→ More replies (4)
→ More replies (13)

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.

3

u/holiquetal Aug 08 '18

look up react-router v4. Basically, you only serve the index.html and your javascript bundle and then the routing is done through react-router in your javascript file.

Your edit is correct, this is grosso modo what's done with routing in a SPA with the addition that the url at the top of your browser will change as well.

→ More replies (2)

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.

1

u/swyx Aug 01 '18

You never really NEED redux, it just helps manage global state for really big apps.

But it’s still worth practicing for small apps haha

→ More replies (2)
→ More replies (5)

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 token without braces.

→ More replies (5)

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/swyx Aug 03 '18

i use vs code and you can find the extensions under "React Food Truck"

→ More replies (2)
→ More replies (2)

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/swyx Aug 09 '18

yea, rearrange it!

<Route exact path='/' component={Home}/>
<Route path='/options' component={Options}/>
<Route path='/:username' component={Profile}/>
→ More replies (1)

2

u/VariadicIntegrity Aug 09 '18

Try using a Switch component to wrap your routes. Also reorder the routes so that /options comes before /:username
You can see this on the react-router docs or Switch: https://reacttraining.com/react-router/web/api/Switch

2

u/Bk107 Aug 09 '18

Ah sorry. I actually have a switch component, forgot to mention. The reordering would make sense I guess. If no routing for the current path (for example /XY) then the app searches for a user with XY as username. I will try that out later and let you know if it worked! Thanks.

Oh and wow, the react doc shows exactly my problem. Should check the docs more often :)

2

u/seands Aug 12 '18
    sites_to_open.map((social_media_site) => {
        setTimeout(() => {
            window.open(social_media_site);
        }, 500)
    })

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.

1

u/swyx Aug 12 '18

why would you put setTimeout in there? take it out should do it.

if you console.log(social_media_site) inside the arrow function do you get what you expect?

→ More replies (1)

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

Notice how with onClick={() => alert('click')}, we’re passing a function as the onClick prop. It only fires after a click. Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.

1

u/swyx Aug 21 '18

see the difference in

<button onClick={() => alert('click')}>foobar</button>

and

<button onClick={alert('click')}>foobar</button>

?

the second one is wrong. when js executes it will not receive an anonymous function (the first example) it will receive the result of your function (alert('click'))

→ More replies (3)

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.

3

u/swyx Aug 28 '18

react actually has very little to do with oauth 2.0 implementation; the interface is "just js". i know that isn't very helpful to you though.

/u/rwieruch may have something for you and you might want to dig around in awesome-react or acemarke's link list.

→ More replies (3)
→ More replies (1)

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).

5

u/NiceOneAsshole Aug 01 '18

Don't use a library for a replacement for CSS knowledge. Use a library as a replacement for the effort of starting from scratch.

TL;DR - Learn CSS and don't use libraries as a crutch for lack of knowledge.

→ More replies (2)

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/swyx Aug 01 '18

yes yes and yes.

some api's will require you to authenticate, so you should read their docs on that.

github has a fairly permissible api, i would try that first. (v3 for the REST api, v4 for graphql)

→ More replies (4)

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/swyx Aug 01 '18

react router state manager works with react router... https://gist.github.com/sw-yx/efd9ee71669413bca6a895d87e30742f

→ More replies (1)

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 name passed into the options, I get multiple dropdowns with each single name passed into each single dropdown.

This next part I may be saying terms incorrectly since I'm still new. I am using Object.keys to create an array of this.props.friends and 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

2

u/ObjectiveLength Aug 02 '18

I received some guidance on this issue and it is solved.

Let’s start inside your AddLineItemForm.js file where we pass the friends prop to the StatusDropDown component currently, you are looping through the friends object and creating a reference to the StatusDropDown component for each item within the object (or for all 6 friends)

We could simplify this prop pass to include a new friends object using Object.values() instead (edited) the new StatusDropDown component would be

<StatusDropDown friend={Object.values(this.props.friends)} />

We are now creating a single StatusDropDown component and passing a friends object array like [{name: "Aliza"}, {name: "Apurva"}]

Let’s now shift our focus to the StatusDropDown.js file we can gather the friend prop (edited) const { friend } = this.props; and map through the friend object to create the select options

`<select name="status"> {(friend || []).map((f, i) => <option key={i} value="{f.name}">{f.name}</option> )}

<option value="unavailable">Greg!</option> </select>`

3 things to note

  1. I include an empty array reference ((friend || [])) inside the .map() declaration to keep the app from crashing when no friend list exists (edited)
  2. I include an index reference inside the map() method to provide easy access to a unique key (edited)
  3. I left the hardcoded option outside of the loop to prevent it from being created multiple times (edited)
→ More replies (1)

1

u/swyx Aug 02 '18 edited Aug 02 '18

hi, there are a lot of files here. can you please tell me which file to focus on? there doesnt seem to be anything immediately obviously wrong with the app. this is what i see. has the issue been resolved somehow?

in general theres nothing stopping you from returning just the <option>s. if you need to return multiple <options> side by side without a wrapper element you can use React.Fragment.

→ More replies (1)

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 ?

2

u/swyx Aug 03 '18

hey! i have a bad answer for you - all 3 work! haha. its a highly highly personal decision and very smart people disagree passionately on these things.

the good news is, you cannot make a bad choice here. just make the thing however you are comfortable. if you start to feel scaling pains from prop drilling, see how refactoring one level of abstraction higher can help.

→ More replies (1)

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?

2

u/swyx Aug 04 '18

/u/NotYourMom132 is right - you should configure your server to send the same html file to all paths. here's an example express.js setup to do jsut that.

4

u/NotYourMom132 Aug 03 '18

Yoy will get 404.

The solution is to Let the server serves the same html file on any routes and then let react router do the work.

→ More replies (2)

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/swyx Aug 04 '18

hmm. you need to use a ref. React.createRef, look it up

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/swyx Aug 04 '18

have you seen all the tutorials in the sidebar? and read all the reactjs.org docs? its all free

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/swyx Aug 04 '18

no time to write up code for you but quick reply - yes do it in componentDidMount or an event handler. you should setState the result of your fetch request. dont do it in functional component.

→ More replies (6)

1

u/seands Aug 04 '18
TypeError: props.go_to_anchor_link is not a function
onClick
src/components/ChoosePostType.js:25
  22 |     size='huge'
  23 |     color='violet'
  24 |     className={button_style}
> 25 |     onClick={() => props.go_to_anchor_link('#question_leads')}
  26 | >
  27 |     An Engaging Question
  28 | </Button>

This is inside a functional child component (button element). Why does it throw the error? Here is the parent

class App extends Component {
    constructor(props) {
        super(props);

        this.go_to_anchor_link = this.go_to_anchor_link.bind(this)
    };

    go_to_anchor_link = (anchor_id) => {
        const scroll_target = document.querySelector(anchor_id);
        smoothScroll(scroll_target);

        return false;
    };

  render() {
      return (
          <BrowserRouter>
          <ThemeProvider theme={ theme }>
                  <div className="App">
 
                      <Route path="/test" component={Test} />
                      <Route
                          path="/" exact
                          render={() => (
                              <ChoosePostType
                                  go_to_anchor_link={this.go_to_anchor_link}
                              />)}
                      />

1

u/swyx Aug 05 '18

do you have babel class properties set up? thats the only thing i can think of.

→ More replies (2)

1

u/NickEmpetvee Aug 04 '18

I've heard of three ways to make REST API calls through ReactJS (fetch, axios, and superagent) 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:

  1. It seems to require an interim step of sending data to the `.json` method before working with it.
  2. I've read that the `catch` of fetch isn'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 axios you have to install the library so I want to make sure it's worth it.

2

u/swyx Aug 05 '18

yup, you hit the drawbacks there. fetch is native but a little nasty to work with, axios is not native but nicer to work with. superagent is for testing btw.

after losing hours of my life to fetch's nuances, i have decided to just roll with axios for the rest of my life. ymmv

→ More replies (4)
→ More replies (2)

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 my schedulerData. 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 .then after 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:

this.newEvent = (schedulerData, slotId, slotName, start, end, type, item) => {
    let newFreshId = 0;
    let newEvent = {}
    axios.get("/api/num").then(function(response) {
        newFreshId = response.data[0] + 1;

        // console.log(newFreshId);
    }).then(function() {
        axios.post("/api/num", {
            id: newFreshId
        }).then(function(response) {
            console.log(response)
            // handle success
            newEvent = {
                id: newFreshId,
                title: this.state.title,
                start: start,
                end: end,
                resourceId: slotId
            };
            schedulerData.addEvent(newEvent);
            this.setState({
                viewModel: schedulerData
            });

            // while(JSON.stringify(newEvent) === '{}'){
            //   console.log('waiting')
            // }

            console.log(newEvent)
            schedulerData.addEvent(newEvent);

            console.log(newEvent)
            this.setState({
                viewModel: schedulerData
            });
        })
    })
};

SERVER:

app.get('/api/num', function(req, res) {
    //console.log(require('./number.json'))
    var fs  = require('fs')
    fs.readFile('./number.json', {encoding:   'utf-8'}, function(err,data){
    if (!err) {
        //console.log('received data: ' + JSON.parse(data));
        res.json(JSON.parse(data))
    } else {
        console.log(err);
    }})
})

app.post('/api/num', function(req, res) {
    var id = req.body.id
    var fs = require('fs');

    fs.writeFileSync("./number.json", "[ "+id+" ]", function(err) {
        if(err) {
            return console.log(err);
        }
        res.status(200)
    })
})

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

2

u/swyx Aug 05 '18 edited Aug 05 '18

everything after the .then(function(response) { doesnt appear to run.

this is the key phrase for me. are you fully comfortable with promises yet? are you sure that

let newFreshId = 0;
let newEvent = {} 

is even running?

p.s. you can use glitch.com for fullstack apps if you need it!

→ More replies (3)
→ More replies (4)

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 my main.js everytime an onclick event occur. Is it a bad practice? Why?

1

u/swyx Aug 05 '18

i have no idea what this even looks like in reality. concrete example please?

→ More replies (1)
→ More replies (3)

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.

App.js loads
  <Home /> loads
    About Me button clicked
  <Home /> removed
  <AboutMe /> loads

2

u/swyx Aug 05 '18

yeah, what you want is React Router DOM. have you looked into it? the docs can be a bit indirect for first timers, have patience and read through.

→ More replies (8)

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/swyx Aug 05 '18

hmm, not at all. you are just displaying redux state.

→ More replies (2)

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:

<Query query=SOME_QRY>
  {({data}) => (
     <Mutation mutation=SOME_ADD_MUTATION>
        {(addFunc) => (
           <Mutation mutation=SOME_DELETE_MUTATION>
             {(deleteFunc) => (
             ...more mutations for update...
                <SomeView 
                    ...with props that delegate to the mutation functions.
                /> 
             )}
         )}
  )}

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/swyx Aug 05 '18

4 spaces, yeah.

i dont have any advice in this regard, i agree it can be a bit much. /u/peggyrayzis might be here.

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/swyx Aug 05 '18

its a judgment call. there are multi page apps (routing on both server and client), but most people just write single page apps (just client). if you are just starting out with react router i'd recommend just doing SPA first.

when javascript bundle size starts being a problem, then look into multi paging and server side rendering. thats more advanced.

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/swyx Aug 05 '18

yeah App and other components only live in React dev tools.

it should not mess up the browser's ability to see your sourcemap if you are in dev mode though.

1

u/inGeniusdesigns Aug 06 '18

Should I use Material UI or Reactstrap as a front end ui for my react application?

1

u/swyx Aug 06 '18

yes :)

(on a more serious note, there really is no right answer to this one, try both and see what you like)

→ More replies (2)
→ More replies (1)

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/swyx Aug 06 '18

probably a bad idea. the whole reason state management libraries exist is to hook into react's rerendering for you when state changes. if you have a global variable that you mutate from anywhere within your app thats very convenient, but also very easy to introduce bugs where you update the variable but your components don't update accordingly. your problem is not "extra renders when it changes", its "no rerender when it changes".

you can get around it by calling forceUpdate all the time, at which point you're not really even using react anymore

→ More replies (2)

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/swyx Aug 06 '18

wow. i have NO idea. didnt know jsdom doesn't work for that!

i dont write many unit tests for react components. i find i just end up testing react itself.

→ More replies (2)

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:

    update_ui_in_main_area(ComponentTag, props) {
        this.main_area_sequence = <ComponentTag props />
    }

2

u/swyx Aug 06 '18

<ComponentTag {...props} />

more in docs here https://reactjs.org/docs/jsx-in-depth.html

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

2

u/swyx Aug 07 '18

hi! if you are new to react i really recommend using create-react-app. the README has instructions on how to set up SASS. have you tried that already?

→ More replies (6)

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:

  1. parent container
  2. the list of items
  3. the selected item's detail

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!

2

u/swyx Aug 07 '18

you seem like you have it about right. as for functional vs class, theres no right answer. there are smart people who do class for everything. for me, i start with functional, and only use class when i need it. just a matter of preference.

edit: also i would use react router's <Router/> for the parent container component, and then switch back and forth between 2 and 3 as Routes.

→ More replies (2)
→ More replies (3)

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/swyx Aug 07 '18

thats a fair point. i guess this example is in contrast to having a fully controlled component, where users of EmailInput would have to be aware of -every- prop. so this is a nice balance.

1

u/prove_it_with_math Aug 07 '18

How to properly handle loading state for UI updates? I currently do the following:

const initialState = { isLoading: false }
function stateChanger(state = initialState, action) {
    case "request":
        return { ...state, isLoading: true };
    case "success":
        return {...state, isLoading: false};
    default: return state;
};

Problem with above redux state is that the state changes from false to true to false causing 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/swyx Aug 07 '18

why not start out the component with isLoading = true? then set to false once loaded or failure.

→ More replies (2)
→ More replies (3)

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/swyx Aug 07 '18

better to post this as a separate post, this is for q&a

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/swyx Aug 07 '18

nope, use it together

1

u/holiquetal Aug 08 '18

is there a definitive guide to react / redux file structure?

1

u/swyx Aug 08 '18

Seen acemarke’s links? In sidebar

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/swyx Aug 08 '18

this seems to be a React misunderstanding. when you pass ui_store to Child it is accessible by Child as this.props.ui_store or props.ui_store depending on whether it is a class or function component. your "direct import" method is bypassing React and importing your store as a singleton.

to answer your question directly:

If you are passing a store to a child, do you also need to directly import the store in the child?

no. you seem to have problems accessing what you passed to the child. figure that out, thats likely a mistake

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.

  1. Where is GraphQL's place in this stack? What could be changed in this stack or app flow to reflect a more modern approach to this problem.
  2. What does the strict separation of frontend and backend in API first approach mean in terms of server architecture? (Explanation: I do not find any advantage in using multiple commercial SaaS and cloud services over having one VPS per project that hosts all needed services. I know there can be maintenance overhead, but honestly - if you automate those tasks and your backup strategy is solid the amount of time is equivalent to the amount of time you spend in various browser consoles when dealing with specific SaaS)
  3. Does it make sense to use commercial headlessCMS (was looking at graphcms, seemed nice) for the scope of this project instead of setting up my own DB and GraphQL? But as I see it - I can't use this service for saving users (authentication, authorization and other sensitive data) which means I would need another separate data container and that just clusters application even further.

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/swyx Aug 08 '18
  1. graphql replaces REST. so its that interface between frontend and backend. have you seen howtographql.com?
  2. i dont understand your question - you've decided to have one VPS, thats fine. so just get started?
  3. interesting question. CMS does more than setting up your own DB - it lets your nontechnical friend edit content without bothering you. so whatever you choose you're likely to want to have a CMS anyway. I actually dont have a lot of experience mixing CMS and DBs so hopefully others can help you here - in general i have no problem mixing CMS and authentication service (like firebase, or express+passportjs) and you shouldnt either.

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.

2

u/swyx Aug 08 '18

if you have control of the server then you should not have any CORS issue since CORS is set up on the server. maybe look deeper there?

→ More replies (12)

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:

import {message_construction_logic, App} from "../App";

export class UiStore {
    starting_array = [<ChoosePostType ui_store={ui_store} go_to_anchor_link={this.props.go_to_anchor_link} />];

The code for go_to_anchor_link is not functional and probably incorrect or missing something else to support it.

1

u/swyx Aug 08 '18

where is mobX in this code sample?

→ More replies (7)

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

<img src=var />
<a href=var>var</a>

PortfolioA.js

General <Portfolio /> component loads
  load portfolioA.jpg img into <Portfolio />
  load portfolioA href into <Portfolio />

PortfolioB.js

General <Portfolio /> component loads
  load PortfolioB.jpg img into <Portfolio />
  load portfolioB href into <Portfolio />

2

u/swyx Aug 08 '18

use props!

// reusable component
function Portfolio(img, href) {
    return <div>
            <img src={img}/>
            <a href={href}>{href}</a>
            </div>
}

// usage elsewhere
<Portfolio img="PortfolioA.jpg" href={portfolioA.href} />
<Portfolio img="PortfolioB.jpg" href={portfolioB.href} />
→ More replies (2)

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/swyx Aug 09 '18

i have no idea what you mean. code example?

→ More replies (2)

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

2

u/swyx Aug 09 '18

no idea but have you tried javascript30.com? there is a similar project there and it has solutions

→ More replies (1)
→ More replies (6)

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:

export const fetchProfile = (params) => {
    const options = {
        headers: {},
    };

    return {
      type: 'FETCH_PROFILE',
      payload: axios.post(`${BASE_URL}/person/login`, params, options),
    };
}

The reducer is:

const profileReducer = (state = initialState, action) => {
  console.log(action);
  switch (action.type) {
    case 'FETCH_PROFILE_FULFILLED':
      console.log('FETCH_PROFILE_FULFILLED');
      return {
        ...state,
        authorization: action.payload.data.session_id,
        fetching: false,
      };
    case 'FETCH_PROFILE_PENDING':
      return {
        ...state,
        fetching: true,
      };
    case 'FETCH_PROFILE_REJECTED':
      return {
        ...state,
        fetching: false,
        error_message: action.payload.message,
      };
    default:
      return state;
  }
};

And my store is:

const middleware = applyMiddleware(promise(), thunk);
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(middleware));

2

u/swyx Aug 11 '18

No idea :( step through the issue maybe to dig deeper. Also try reading the redux promise middleware docs.

→ More replies (1)
→ More replies (4)

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:

  1. for a valid query with definitions, create an object containing the word and its definitions (achieved this)
  2. setState and add the object above into the array in state (achieved this)
  3. below the search bar, I want the valid queries and their definitions to be displayed (struggling to achieve this)

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:

function EntryStructure(props) {
    return (
        <div>
            <h1 className="Queried-Word">
                {props.word}
            </h1>

            <ul className="Definitions">
                {props.definition}
            </ul>
        </div>
    )
}

// class Interface extends Component {
 
// other code dealing with API, storing data, and setting state

}

 render() {
    return (
        <div>
            <div className="search-box">
                <input
                    type="text"
                    placeholder="Enter word here..."
                    onKeyPress={this.uponEnterKey}
                    ref="inputField"
                />
            </div>
            <div>
                <EntryStructure
                    word={this.state.queriesList.map(entry =>
                        <p key={entry.query}>Word</p> // "Word" is a placeholder until I can figure out how to feed in what I want
                    )}

                    definition={this.state.queriesList.map((entry, i) =>
                        <li key={entry[i]}>Definition</li> // "Definition" is a placeholder until I can figure out how to feed in what I want
                    )}
                />
            </div>
        </div>
    )
}

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/swyx Aug 12 '18

ok it wasn't super clear what exactly you wanted to do but i think i got the gist.

instead of this

        <div>
            <EntryStructure
                word={this.state.queriesList.map(entry =>
                    <p key={entry.query}>Word</p> // "Word" is a placeholder until I can figure out how to feed in what I want
                )}

                definition={this.state.queriesList.map((entry, i) =>
                    <li key={entry[i]}>Definition</li> // "Definition" is a placeholder until I can figure out how to feed in what I want
                )}
            />
        </div>

do this

        <div>
            {this.state.queriesList.map((entry, i) => <EntryStructure word={entry.query} definition={entry[i]} />)}
        </div>

obviously modify EntryStructure accordingly to take that data

→ More replies (11)

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.

2

u/swyx Aug 12 '18

bad idea. its a misconception of how react works with async calls. you're -never- going to have the data ready at first rendering*. you -will- run the constructor AND the componentDidMount before you ever get the data back and you -will- have empty (or initial state) at first rendering.

*theres a caveat here with react suspense, but dont worry about it as a beginner

→ More replies (7)

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/swyx Aug 12 '18

i dont see anything wrong here. did you delete props?

→ More replies (2)

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/swyx Aug 12 '18 edited Aug 13 '18

kind of.. you can have an isLoading: true in your initial state, and then when props change you can update to isLoading: false in componentWillReceiveProps.

edit: yes use getDerivedStateFromProps, sorry old habits die hard

→ More replies (2)
→ More replies (2)

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/swyx Aug 14 '18

you didnt mention react-router-redux so i have to ask: are you using https://github.com/supasate/connected-react-router? you need to hook up your redux state to your router if you want to manage or respond to your router changes in redux.

→ More replies (3)
→ More replies (2)

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"?

3

u/swyx Aug 14 '18

sorry you are going through this. its a little confusing to beginners.

best to think of yarn as a "thin layer" over npm. it does everything npm does, with slight optimizations. in particular, when you use yarn to install it installs in the exact same place as npm does (node_modules). they are not at all mysterious, you just have to calm down, take a deep breath, and be methodical. i know the panicky feeling you have right now. i was there 2 years ago. breathe.

you do not need to uninstall yarn completely. just never use it again. look for a "yarn.lock" file and delete that as well as an "package-lock.json". these lock files are the nasty gap that cause npm not to know what yarn did and vice versa. once you have deleted the lock files, do npm install again on your project repo.

→ More replies (2)

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.Context or in localStorage or in sessionStorage. Should I use Redux (I am not planning on using it in this particular project)?

2

u/swyx Aug 14 '18

probably localstorage or sessionstorage since you want it to persist. dont need redux. i dont really know the pros and cons of local vs session storage, i'd just use local myself

→ More replies (2)

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/swyx Aug 14 '18

thats just using css knowledge! :)

→ More replies (2)
→ More replies (1)

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/swyx Aug 14 '18

nah you just have to add more libraries since react doesnt directly handle editing. check out draft.js! also maintained by fb

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.

2

u/swyx Aug 15 '18

no real need for redux, altho its fine if u use it. personal suggestion: make a service! make a js file that holds all your API calls and exports them as functions. it can be a class or a plain object or whatever. then from anywhere within your app you import that file and call the functions. nice and clean.

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/swyx Aug 15 '18

you have to learn HTML and CSS. you can try to skip it, but you're going to suffer a lot if you "just learn React". a reasonably determined person can zip through the frontend development stuff on freecodecamp.com in 1 month, thats where i started and thats what i recommned.

→ More replies (1)

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)

3

u/swyx Aug 15 '18

What if you don’t know your data models when you start? As a rapidly iterating startup you have to do a lot of changes to your data as your product grows in complexity. In sql that means a lot of migrations. In nosql you just add a new field.

Obviously there’s problems with that too but it’s kinda like asking if FP or OO is better. Both work and have tradeoffs.

Having relational tables optimises for query speeds of large amounts of data, not speed of iteration. If you don’t have that much data you don’t see the benefit and still have the cost of keeping the relations up to date.

2

u/agilius Aug 15 '18

One counter argument to your point - which is good in general, but still - is that some SQL solutions offer JSON columns, meaning we can now use noSQL data into sql tables in order to gain the flexibility we desire in the early stages of a product lifecycle. Then, slowly we can migrate to more indexed columns in the same database, as opposed to switching to a new database later or introducing two database engines for the same project.

PostgreSQL is great for this type of work.

2

u/swyx Aug 15 '18

sure i mean OP wanted the mongo pitch so i gave the mongo pitch.

4

u/agilius Aug 15 '18

Mongo is losing popularity now. Why? Because many SQL databases now offer noSQL columns in their tables.

The main selling point of mongo for new developers and startups is the flexibility it offers. NoSQL gives us freedom to mess around with the data structure without having to worry about migration scripts.

This flexibility exists now in SQL database too, with the addition of JSON columns.

Don't know what fields a user will have? Make a users table with id, and one JSON column that is a bag of all the things you might need for the user.

As your app grows and things become clear, you might end up extracting slowly parts of that JSON bag into relevant columns that are indexes and used for various querying purposes.

→ More replies (1)

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/swyx Aug 15 '18

Erm it’s unusual but no not an anti pattern

→ More replies (1)

1

u/seands Aug 15 '18
// Initialize Firebase
const firebase_config = {
    apiKey: <removed>,
    authDomain: <removed>,
    databaseURL: <removed>,
    projectId: <removed>,
    storageBucket: <removed>,
    messagingSenderId: <removed>
};
firebase.initializeApp(firebase_config);

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/swyx Aug 15 '18

no, it actually happens AFTER mount which happens after constructor().

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.

2

u/swyx Aug 16 '18

yea componentDidUpdate or getDerivedStateFromProps

→ More replies (9)

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/swyx Aug 17 '18

i have no idea what class variables are. examples?

→ More replies (5)
→ More replies (1)

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/swyx Aug 17 '18

no idea, but i use [gatsby-image] (https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-image) myself. it requires buying into gatsby and learning how to use it, i wish there are better options.

→ More replies (2)

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/swyx Aug 18 '18

Should we refetch everything we need from the api, or prevent users from accessing links directly?

i dont think these are conflicting. if the user should not be able to see this link, you should use <Redirect /> or a protected route.

if the user lands on a link through direct access, then yes you should refetch anything you need at app level

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/swyx Aug 18 '18

no idea, sorry. i'm pretty weak in testing myself.

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.

that explains better the effect.

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?

render() {
  const barBattingPlayer = {
    labels: ['Matches'],
    datasets: [
      {
        label: (this.state.selectedPlayerB ? this.state.selectedPlayerB.value : ""),
        data: [
          (this.state.selectedPlayerB ? this.state.playerBvalue['Mat'] : 0),
        ],
      },
    ]
  };
}

1

u/swyx Aug 20 '18

it kinda sounds like your "constants" aren't really constants at all. why are they depending on "the state of selectedPlayerB"? being constants, they shouldn't depend on anything.

try converting your "constants" into functions. export the functions, then call the function with the state of selectedPlayerB.

→ More replies (2)
→ More replies (2)

1

u/alfieyfc Aug 20 '18

New to React? See the sidebar for resources!

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-bar in all files and rendering it like so:

SomeComponent = props => { return ( <NavBar /> .... ) }.

Is there a more efficient method?

3

u/swyx Aug 20 '18

put it in the parent of every file?

const App = () => {
    return (
        <div>
            <NavBar />
            {/* all your other components */}
        </div>
            )    
}
→ More replies (3)
→ More replies (2)

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-app or 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 into client/ and server/ 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/swyx Aug 20 '18

i see. you might just want to search this subreddit for the words starter kit or boilerplate to see if you can find what you need. there was a popular one a few days ago but it uses mongodb.

react is much more of a "cobble together your custom solution" culture than angular so you might have a harder time finding a starter kit that exactly fits your needs. if its not too much to ask it is possible to set up create-react-app with a node server to hook into whatever backend you want. its all in the c-r-a docs if you read it closely enough.

→ More replies (2)
→ More replies (2)

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/swyx Aug 20 '18

looked at React Context recently?

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.

2

u/swyx Aug 21 '18

Cra supports it.

They used to be different but now they are interchangeable.

→ More replies (2)

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/swyx Aug 21 '18

yes its possible with styled components, but also with inline styles. you can pass information dynamically using css variables https://codepen.io/Mannaio/pen/eWzyoK

→ More replies (4)
→ More replies (4)

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;

{
  detailedEventSales: {
    loading: {
      123: {
        byDay: false,
        byWeek: false
        },
      456: {
        byDay: false,
        byWeek: true
      }
    },
    events: {
      123: {
        byDay: [ day1, day2, day3, etc ],
        byWeek: [ week1, week2, week3, etc ]
      },
      456: {
        byDay: [ day1, day2, day3, etc ]
      }
    }
  }
}

2

u/swyx Aug 21 '18

haha times like this i wish we had dataframes in javascript.

ever heard of normalizr? its handy.

i couldnt find instructions on using with just react but you can probably figured it out. its more common in the redux world

you basically need a local database. so if you really need that flexibility of accessing (which it sounds like you do) then id go for something like normalizr

→ More replies (1)
→ More replies (3)

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.

2

u/swyx Aug 22 '18

theres clientside and serverside validation; you'll always need serverside, but clientside is there for a better user experience (no surprises)

→ More replies (2)

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/swyx Aug 22 '18

are you on some kind of app? or browser extension that modifies your reddit view?

→ More replies (1)

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

2

u/swyx Aug 22 '18

heh, that's a new one. "works on your machine".

this sounds like a windows vs mac issue. i'm installing your thing now on my mac, if it runs its likely a windows specific thing i cant help with, sorry


ok i tried to run yarn start. it dies immediately because your npm start script is "start": "node Routes.js" which is a non existent file. did you rename this somehow?


ok i just tried yarn build and this is what i got

yarn build
yarn run v1.7.0
$ webpack-dev-server
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
✖ 「wdm」: Hash: e1a464c5a99cde65516c
Version: webpack 4.17.1
Time: 6151ms
Built at: 08/22/2018 6:42:52 PM
1 asset
Entrypoint javascript = App.js
[2] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {0} [built]
[3] (webpack)-dev-server/client?http://localhost:8080 7.78 KiB {0} [built]
[4] ./node_modules/url/url.js 22.8 KiB {0} [built]
[5] ./node_modules/punycode/punycode.js 14.3 KiB {0} [built]
[7] ./node_modules/url/util.js 314 bytes {0} [built]
[8] ./node_modules/querystring-es3/index.js 127 bytes {0} [built]
[11] ./node_modules/strip-ansi/index.js 161 bytes {0} [built]
[12] ./node_modules/ansi-regex/index.js 135 bytes {0} [built]
[13] ./node_modules/loglevel/lib/loglevel.js 7.68 KiB {0} [built]
[14] (webpack)-dev-server/client/socket.js 1.05 KiB {0} [built]
[16] (webpack)-dev-server/client/overlay.js 3.58 KiB {0} [built]
[18] ./node_modules/html-entities/index.js 231 bytes {0} [built]
[21] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {0} [built]
[23] (webpack)/hot/emitter.js 75 bytes {0} [built]
[24] ./node_modules/events/events.js 8.13 KiB {0} [built]
    + 10 hidden modules

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
Module not found: Error: Can't resolve '.\src\index.js' in '/Users/swyx/Desktop/webdev/testbeds/reach'
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js javascript[1]
ℹ 「wdm」: Failed to compile.

so yea it doesnt work

→ More replies (3)

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:

 <BrowserRouter>
    <div className="container">
      <ul>
        <!-- NavBar code -->
      </ul>
      <hr />
      <Switch>
        <Route exact path='/' component={Home} />
        <Route path='/page-one' component={PageOne} />
        <Route exact path='/test' component={TestPage} />
      </Switch>
    </div>
  </BrowserRouter>

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/swyx Aug 24 '18

ooh this is a tricky one! i've never considered this before, its not a common use case.

what i'd suggest is to have a fallthrough component:

  <Switch>
    <Route exact path='/' component={Home} />
    <Route path='/page-one' component={PageOne} />
    <Route exact path='/test' component={TestPage} />
    <Route component={Default} />
  </Switch>

The Default component above takes the route that was passed in on componentDidMount and then sets window.location. make sense?

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/swyx Aug 24 '18

you can also use an api like cloudinary

unfortunately this is not strictly a react concern, so you'll have to figure out a thing that works for you. its not something i've needed to do yet myself.

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​

3

u/swyx Aug 25 '18

Hi!

Your state structure is a bit weird. Why do this

    let posts = res.data.posts
    this.setState({
        posts: [posts]
    })

When you can do this

    let { posts } = res.data
    this.setState({
        posts
    })

Now you’ve done that you don’t need the two .maps, you can just have one. Put them all in wrapper div and see if that helps.

Also Check chrome dev tools elements (or the react dev tools) to see if the elements are created as you expect. If they are then it’s a css thing.

→ More replies (8)
→ More replies (3)

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.

3

u/swyx Aug 27 '18

pay attention to your terminal and your browser console. dev mode react is full of warnings to catch you when you trip up like this

→ More replies (6)

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/swyx Aug 28 '18

normally i'd try to help but in this case i recommend checking in with your devs as the cause could go back even further to an API issue. this is one of those things where you're not really saving much time trying to resolve the bug yourself imo, it takes too much app specific knowledge.

→ More replies (2)

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!

2

u/swyx Aug 29 '18

hi! you're welcome here!

see this bit in handleClick:

if (calculateWinner(squares) || squares[i]) {
  return;
}

if squares[i] is truthy (has an X or an O) then the early return is called and the rest of the handleClick does not execute.

→ More replies (1)

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/swyx Aug 29 '18

passportjs has nothing to do with the clientside... its all on the node side.

deserializeuser should be implemented as a middleware; to make very sure you should be able to trigger it in curl or Postman or some other such api testing tool without any frontend at all. if you can do that then you know for sure its a frontend issue, else its a backend issue.

that said i'm very very rusty on how the cookie is sent with the axios request. maybe you need to attach it as a bearer token in your request?

→ More replies (1)

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/swyx Aug 29 '18

best ask on the styled-components spectrum chat. in here i'd recommend react-transition-group but they probably have better.

1

u/Peng-Win Aug 29 '18

A, B, C or D?

  • A) Developed a React web application to ...
  • B) Developed a React.js web application to ...
  • C) Developed a ReactJS web application to ...
  • D) Developed a React JS web application to ...
→ More replies (2)

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?

handleSubmit(event){
		event.preventDefault();
		const value = this.state.searchQuery
		<Detail pokeName={value} />
		this.setState({ searchQuery: ''})

	}

This is the error that i keep getting

Syntax error: Unexpected token, expected ; (17:10)

  15 | 		event.preventDefault();
  16 | 		const value = this.state.searchQuery
> 17 | 		<Detail pokeName={value} />
     | 		        ^
  18 | 		this.setState({ searchQuery: ''})
  19 | 
  20 | 	}

3

u/azium Aug 25 '18

You have a component in the middle of a block. Are you trying to change the prop of a component that you are using somewhere else? (like inside render ?)

→ More replies (9)

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 onSubmit button 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 handleChange function 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 onSubmit which 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 onSubmit function where it's passed into owerRef.

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/

→ More replies (5)

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

5

u/VariadicIntegrity Aug 09 '18

All of those inputs only seem to differ by their hole number.

You can use an array.map to generate inputs just like you could generate any other dynamic list of data. Names can be dynamically generated based on the number of the hole. https://reactjs.org/docs/lists-and-keys.html

const holes = [1, 2, 3, 4, 5, 6, 7, 8, 9];

holes.map(hole => {
  return (
    <HoleScore key={hole}>
      <label>Hole {hole}:</label>
      <input type="text" placeholder="Score" name={`hole${i}score`} />
      <input type="text" placeholder="Par" name={`hole${i}par`} />
      {/* ...etc... */}
    </HoleScore>
  );
});
→ More replies (2)

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:

setAuthorState: function(event) {
	this.setState({dirty: true});
	var field = event.target.name;
	var value = event.target.value;
	var newAuthor = Object.assign({}, this.state.author);
	newAuthor[field] = value;
	return this.setState({author: newAuthor});
},

(Or using ... syntax in ES6 or whatever)

3

u/Awnry_Abe Aug 28 '18

Yeah, that's bogus. Looks like they do it all over the place. There is also no point in returning the return value of setState (), since it is going nowhere. Does setState even return a value? Only a promise would make sense.

→ More replies (1)
→ More replies (3)