To me learning redux from Dan Abramov himself was extremely useful, he goes through the whole thing from first principles and shows a lot of best practices along the way. I didn't just learn redux inside out but also a lot about javascript and functional programming, I really can't praise it highly enough
There is a section in react docs explaining the motivation behind the hooks.
Hooks are not just replacement for class components lifecycle. It's a way of solving a problem. The problem of reusing stateful logic between components. With class components, we were solving this problem using render-props and higher order components, which was far from ideal.
>To some degree, I think Redux is somewhat to blame, with each object needing global state being wrapped in a Connect component. As such, inspecting a React tree is often nearly twice as long than it feels like it needs to be.
This is called "Wrapper Hell". We all have felt that pain.
> It’s also not always clear where the data is coming from that is populating a component. Sometimes it’s five levels up being passed down through rested props.
This is called props drilling. You're giving me the impression this codebase was a little gnarly.
>I’ve often found myself hopping on a call with a co-worker, someone who has been with the company and the code much longer than I have, to be told, “yup, that should probably be refactored.”
There ya have it folks. If you don't keep your code clean, it will be very painful to onboard new talent, even very patient, new talent. Ideally React components will allow you to take things one at a time, but honestly since components provide you so much freedom, there's plenty of ways to write in patterns that create a rats' nest very fast. Even Redux can't save you then. OP, it's important to recognize the changes you can make, but also the difficulties that did not originate with you.
Took me longer to learn than i’d like to admit. Personal tip: Learn and understand redux independent of React, then learn to incorporate it into React. Especially if you’re new to React. Dan Abramov, creator of redux, has a great and thorough tutorial
State updates maybe Asynchronous
Following your example above, setState(state + 5) will just add 5 to state, but we know that setState is actually asynchronous and is sometimes batched together with other setState calls by React to boost performance.
if we had multiple setState(state + 5) calls, and they got batched together, state won't change until the whole batch is finished. So if lets say state is 10, the result would be:
setState(10 + 5) setState(10 + 5) setState(10 + 5)
Instead of adding 15 to our state it would only add 5 in the end. That's where we want to pass an anonymous function.
setState(current => current + 5)
If we call this multiple times and they got batched together...
setState(current => current + 5) // current is 10, we return 15 setState(current => current + 5) // current is 15, we return 20 setState(current => current + 5) // current is 20, we return 25
We would have added 15 to our state, even when it was batched.
Not really any critique, but some quality of life improvements.
You might prefer using something like CodeSandbox for doing React dev online. It lets you create files to separate your components into so it's easier to reason about.
Also, you should look into object destructuring assignment. It allows you to pull variables out of an object much quicker and is pretty common in React development, so you'll likely run into it.
This
const types = props.pData.types;
const stats = props.pData.stats;
const moves = props.pData.moves;
Turns into this
const { types, stats moves } = props.pData;
Components can be really simple, especially with functional components. These can really simplify the code and make the user interface more consistent across the application. However, I have to agree with you that using existing Bootstrap classes or React-Bootstrap might be a better solution here.
Yes, you should prefer using function components for everything today. Class components still work, but you really shouldn't be writing any new class components.
FYI, the React team has been working on a complete rewrite of the docs to teach function components + hooks as the standard approach for writing React components. Those should hopefully be going live fairly soon.
For more details, see:
The change is pretty subtle. Accessibility could be a thing.
Also the progress bar feels disconnected from the controls. It's at a higher level in the visual hierarchy, which is sort of opposite what you'd expect.
Last note is that the "play" button feels like the wrong icon. This would make sense as an audio player, but for an upload I would expect the standard upload icon. (https://fontawesome.com/v4.7.0/icon/upload)
Very clean design, and nice colours. There's lots to like about it.
From the docs:
>We intend for Hooks to cover all existing use cases for classes, but we will keep supporting class components for the foreseeable future. At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.
The second part that is commented out is the correct usage, you just have the wrong type. React has a wrapper around the native event types, https://reactjs.org/docs/events.html, so you just need to change Event to the corresponding react synthetic event type.
Facebook doesn’t recommend rewriting classed based components. I usually don’t either unless I am fixing bugs in an existing component or adding additional functionality. See here https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both
What is the point of these articles? The same exact topics get rewritten and reposted seemingly several times a week. But somehow, the official docs are still the best and most comprehensive source of information.
In my experience, it isn't worth it writing unit tests for components, specially if you're working on a rapidly evolving project (which is the case for most startups).
If you have complex logic in your components, I suggest you to abstract it into small functions and unit test them.
Something that is worth doing is end-to-end tests. In this case, you should take a look at https://www.cypress.io
A component is a function and, as such, can call itself recursively. For instance, this would render this data structure with any level of nesting:
const Tree = ({ data }) =>
data.map((item) => (
<ul>
<li>{item.title}</li>
{item.sections && (
<li>
Sections:
<Tree data={item.sections} />
</li>
)}
</ul>
));
Codesandbox example: https://codesandbox.io/s/thirsty-lichterman-o2tk7?file=/src/App.js
>...This approach enables the declarative API of React: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app.
React Docs - Virtual DOM and Internals
Describing the desired state of UI is the declarative approach.
Manually updating DOM step by step to reach the desired state of UI is the imperative approach.
WAIT... so they closed a $102M round in June:
https://vercel.com/blog/series-c-102m-continue-building-the-next-web
and now a $150M round?
https://vercel.com/blog/vercel-funding-series-d-and-valuation
That's nuts!
I've always liked the post Build Yourself a Redux as the best example of a "build a mini Redux" genre.
Also, our new "Redux Fundamentals" core docs tutorial walks through the underlying concepts and how to use Redux logic from the ground up, and I'd encourage folks to read through it. Among other things, it shows both a mini working version of a Redux store in about 25 lines, and how UI layers like React-Redux handle subscribing to the store and updating the UI.
I've almost finished this side project I've been working on for a while!
For years I’ve wanted a clear way to know if a show improves or worsens over time. So I made this! More for fun than anything else 😃.
Any feedback is very welcome!
There's still a few bugs to iron out, and more tests to write, but it's mostly done feature wise:
🔹 Episode rating graph
🔹 "Where to watch" info based on your location
🔹 Best & worst episodes
🔹 Episode summaries
🔹 Similar shows
It also uses some awesome libraries / tools: Zustand for app state, EmotionCSS for complex styling, Cypress for some light e2e tests, Storybook for component library, react-element-query for container queries. I also tried out Plausible which has been great! 👍
The Game of Thrones chart is pretty funny, big nose dive in the end! 😅
I am not selling anything, is free 100%, as you can read in your title.
No need to register or anything, gosh I am not even tracking you because I use umami.is as analytics...
Enjoy them if you need fin any use of it :-) have a great day!
>This rollout is very strong guidance against those who intended to use Suspense for everything. In particular, creating a resource outside of Relay is not documented (altho fakeApi shows the essentials)
Think of Suspense as a car engine. We've made an engine. Making that engine turned out to be hard. But the hardest problems were not related to fetching per se. Figuring out these patterns took such a long time, and yet they're completely independent of Relay.
Think of Relay as a car. It operates on a different level. It integrates with Suspense, but it's its own thing.
What we released is a car engine, and one possible car built with it. We want to make it clear there are many different cars that you could build with that engine. We want people to try building them. And also that the "toy car" we used to demo the engine two years ago is not the actual thing to use.
Hope that makes sense.
JSX isn't HTML. A `<p>` tag in JSX isn't the same thing as a `<p>` tag in HTML and this demonstrates a little bit of a lack of understanding of what JSX actually is. In React, you aren't creating DOM elements or writing HTML yourself at all. You're issuing calls to `React.createElement`, which is what JSX is. It's syntactic sugar around calls to `React.createElement`. When you write JSX, you indicate the "type" which is another component or an HTML element, props, and children. They're just function arguments. In a web application, React handles the actual management of the virtual DOM elements, and the modification of the actual DOM via `react-dom`.
​
JSX isn't HTML, or an HTML replacement. It's a familiar syntax that was added to the framework because the alternative is having gross deeply nested calls to React.createElement all over your project. Feel free to use createElement instead of JSX if you want - it works just fine.
This will be worth a read: https://reactjs.org/docs/hooks-intro.html
They let you write all your React components as functional components, rather than as classes. They change the way your React components interface with their state and with their own lifecycle.
Just a heads up, it seems like you’re using string concatenation to create the bg and text color class names. This will trip up purgeCSS when building for production.
https://tailwindcss.com/docs/optimizing-for-production#writing-purgeable-html
Erm... there's an entire page on how to do that:
https://reactjs.org/docs/hooks-custom.html
and it basically boils down to "cut code that calls some hooks from a component, write const useMyNewHook = () => {}
, paste code inside".
In all seriousness, what do you feel the current docs page doesn't cover sufficiently about this?
The Egghead Kent C Dodds React course is great. It’s very modern(based in hooks) and is only 2 and a half hours long. Would recommend watching that and messing around with a project to learn react!
Link to the course here: https://egghead.io/courses/the-beginner-s-guide-to-react
TY for v12 Next.js Team!.
Looks the the upgrade won't be hard due to small # of breaking changes (depending on projects but not for me ;p )
Time to enjoy the faster rebuild/refresh w/ Rush compiler.
Props and state are not interchangeable. Props are the API of your components, i.e. their public interface. State is private to the component.
In a React application you need some sort of state, and there are many solutions to this. However you do not get far with good coding practices, if you also do not use props.
It sounds like you may benefit from learning about pure components. Unfortunately I don't know what's the best up-to-date resource on this topic, as things have changed quite a lot since just a few years ago. Notably, class components are hardly used anymore.
Maybe the official Tutorial is a good place to start
idk if y'all seen this and are sick of it already haha but i turned my recent exercise into a 25 minute talk.
it has some nice bonuses for those willing to stick through to the end ;)
AMA i guess
If SSR and code splitting aren't helping there's not that much that can be done in terms of performance. Gatsby really only does the same job as SSR, except renders every possible page (& page metadata) on build time which would improve the initial paint time.
What do you really mean by load time? Are you talking about the time-to-interactive or the initial paint? Gatsby and SSR solutions will really only help you get the initial paint time as low as possible but for better time-to-interactive you'll need to look at your JS execution path. There's many aspects that could be causing a slow application, for example:
> drop between two different lists/source
Yep! The best place to start with the project is our free egghead.io course. In the course I guide you through building a Trello like task application - which includes moving items between lists
Because you want to animate when components enter or leave the DOM you need to use ReactCSSTransitionGroup. You say you find their documentation confusing so I will try to explain what it does.
When a component enters or leaves the DOM, ReactCSSTransitionGroup adds a CSS class to it for the time it enters/leaves. This way you can style the animation during the time it enters/leaves. This is code from the docs:
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items} </ReactCSSTransitionGroup>
Items is a list of React components. Whenever something is added from items, it will add the class example-enter
to that component. Whenever something is deleted from items, it will add the class example-leave
to that component. Then you can style those classes. This is styling from the docs:
.example-enter { opacity: 0.01; }
.example-enter.example-enter-active { opacity: 1; transition: opacity 500ms ease-in; }
.example-leave { opacity: 1; }
.example-leave.example-leave-active { opacity: 0.01; transition: opacity 300ms ease-in; }
Does that clarify anything? If not, please ask again and I will try to improve my answer :)
> designers who only know HTML and CSS
If your project absolutely needs designers to edit HTML without dev interaction, Vue is hardly the right choice. Jquery maybe.
Two examples from the Vue documentation; I have no idea what kind of designer gets this but not JSX
Grid
<table> <thead> <tr> <th v-for="key in columns" @click="sortBy(key)" :class="{ active: sortKey == key }"> {{ key | capitalize }} <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'"> </span> </th> </tr> </thead> <tbody> <tr v-for="entry in filteredData"> <td v-for="key in columns"> {{entry[key]}} </td> </tr> </tbody> </table>
Elastic Header
<div id="app" @touchmove.prevent> <draggable-header-view> <template slot="header"> <h1>Elastic Draggable SVG Header</h1> <p>with <a href="http://vuejs.org">Vue.js</a> + <a href="http://dynamicsjs.com">dynamics.js</a></p> </template> <template slot="content"> <p>Note this is just an effect demo[...]</p> </template> </draggable-header-view> </div>
https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
TLDR; The cleanup function is used to close subscriptions to external data sources or event listeners, to avoid memory leaks
The documentation shows that you can and should use useState and useEffect together, and there is absolutely no problem with that. You can use useMemo for expensive calculations, not for simple variable changes because it's just one more layer of code.
I would start with the official docs, there is a tic-tac-toe tutorial that was created as an intro to react. Material-ui is mostly a set of react components based off googles material design principles. Kinda like a fancy css framework.
> 2) Know Thy HTML: ... JSX is still HTML so be sure is valid HTML!
Well that's just wrong. JSX is definitely not HTML.
JSX is syntactic sugar for JS function calls.
The second page of the React docs introduction even says this:
> Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
The Egghead page says "last updated 9 months ago", and you can see it specifically covers React hooks:
https://egghead.io/courses/the-beginner-s-guide-to-react
You should also check out the new React beta docs as well:
We wrote a whole blog post about the legacy lifecycles (technically not deprecated yet) and the migration strategy for them.
https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
Note it's also possible to keep using them (if you must) even in React 17, but you'll need to add an UNSAFE_
prefix to them. This can be done by an automated tool we also released.
You can't hide anything on FrontEnd. Even if you use environment variables, they will be accessible from the browser's source panel.
Regarding Firebase API keys, it's totally fine to be exposed, Firebase uses the keys to just identify the project, Authorization access control stuff is done from the Firebase panel by security rules. also, there are a few specific services that require some extra steps.
I'll suggest reading this to get more information in detail.
Link
simple really. you use cleanup functions. here's a simple example
useEffect(()=>{ let mounted = true; (async () => { const data = await requestData();
if (mounted) { setData(data) } })()
return () => { mounted = false } }, [])
https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1
The hooks FAQ specifically answers that one:
https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
Also not sure what you're expecting them to "rethink". The APIs exist, and aren't going to change meaningfully at this point.
With the addition of Hooks, there are very few reasons for class-based components.
That’s also the recommendation of the React team: https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both
Actually at this point is neither OS nor hardware.
The Developer Transition Kit had an A12Z that did not have virtualization extensions enabled. That shouldn't have stopped the Docker team from being able to port onto Apple's hypervisor framework (frankly, something I'm surprised they hadn't already done, and should have done some time ago), but it would have prevented testing on the ARM platform. M1 does have those extensions enabled.
Right now, it's mainly upstream dependencies that are holding them back. Go will not support Apple silicon until 1.16 due in February (though I expect Docker can start working on it now -- as far as I can tell everything needed for Go to support Apple Silicon is on master now).
They also call out Electron, which is already shipping beta versions with Apple silicon support, but again, they probably don't want to make a production release on prerelease upstreams, not to mention it's a major version so there are probably breaking changes that need to be worked through.
Finally... they actually need to get machines to test on.
So yeah, I'm as antsy as the rest of you... but these things take time, and Docker is in a bit of a unique position simply because it uses virtualization, which is pretty much the one thing that Rosetta can't help with.
The blog post has more details: https://www.docker.com/blog/apple-silicon-m1-chips-and-docker/
Hey, I just uploaded a new screencast on building a Slack-like chat application with React and Chatkit. I also wrote up the tutorial if you prefer text :)
I hope it's interesting to watch me tackle the Slack clone - building a complete application with React and Chatkit.
This video took around 20 hours to make 👀 and watching it back, there's so much I would improve. I would love your feedback for next time as well!
Any questions, please hit me know here or in the YouTube comments! I respond to everyone.
First thing that I would recommend is to *not* store your JWT in local storage. It leaves your app open to XSS.
See this link for more details: https://auth0.com/docs/security/store-tokens
This is a copy paste job from the react docs: https://reactjs.org/docs/refs-and-the-dom.html
In the article he states:
When Should I use Refs? We advise to use refs in the following situations:
Integrating with third-party DOM libraries. Triggering imperative animations. Managing focus, text selection, or media playback.
In react docs it states:
When to Use Refs There are a few good use cases for refs:
Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries.
I’m aware that you can do this but it doesn’t necessarily mean that you should do it.
The context is performance optimisation and that’s literally what useMemo is for.
You can argue and down vote all you want, it won’t change this fact.
Honestly the official intro resources are no longer recommendations in my eyes (with one exception). Instead, look to the resources on the sidebar of this subreddit, particularly Kent Dodds' course for beginners. He also explains why it was created and what problems it's solving.
Fundamentally, React asks you to shift your mentality towards components. This is reflected in almost every corner of react and why it does things the way that it does. That's where the one exception I have above comes in because the official site does break down the usual process of "componentization" through this link https://reactjs.org/docs/thinking-in-react.html. But again, this is so much easier to understand if you know javascript already.
Our pricing is more flexible now and we updated our pricing page to make limits more clear (like 1TB of bandwidth for Pro). We're researching other improvements and I'm open to feedback (feel free to DM me here or on Twitter).
I'll give a shout out to Kent C. Dodds' excellent The Beginner's Guide to React. It goes over the basics in short videos, and progressively builds up a great fundamental understanding of the problems that React is built to solve.
egghead.io also has a large amount of free react courses - in the format I like screencasts to be...very fast and concise.
When I was starting out with Redux and testing react apps I found the tutorials to be very helpful, not sure how good the entry-level course is...but Kent Dodds is a good instructor.
Hello Reddit 👋! I built CodeSandbox, I recommend checking https://hackernoon.com/codesandbox-an-online-react-editor-b8945ce095d2 for more information.
We've also been hunted on ProductHunt today 😀.
I'm here to answer any questions.
Computed property name.
Also the technique is specifically listed in the React Docs for handling multiple inputs: https://reactjs.org/docs/forms.html#handling-multiple-inputs
Yes, it's called a fragment, basically sugar for a static array return. You need babel 7 i believe to do this, otherwise you can use <React.Fragment> ... this one would also allow you to pass a key.
Not related to the question directly.
YTSearch
would be better to be called within componentDidMount.
Refer to this short post: Where to Fetch Data: componentWillMount vs componentDidMount.
I have experience with VueJS so I was familiar with most of the concepts and backend.
My starting point was ReactJS docs. After reading this I immediatelly started building. The other libraries I've learnt on the go from their home pages. As it's a pet project I didn't have to hurry. I've tried several different approaches to the same problem until I was happy with the result.
When it comes to PWA I didn't really need to learn too much. Create react app provides decent service worker for offline-first sites.
So there's two main part you are asking about: code generation to give your user access to a list, and then the realtime part. Both require backend support. You can use something like Firebase or Supabase for that.
Both are capable of setting up listener for real time updates to the data stored. So when some data changes you'll get notified in the React app, and you can display the change.
For the code generation part you'll probably want to generate a code that's stored in the backend, and only gives access / redirect users that do have the code to the list.
react-router
+ separate but reusable presentation components is the way to go. If you got hung up on prop drilling issues check out the React Context API, it's pretty great and solves that issue very cleanly and doesn't require any additional packages.
Uh... are we reading the same docs site?
https://reactjs.org/docs/context.html literally says, as the subheader:
> Context provides a way to pass data through the component tree without having to pass props down manually at every level.
There is a note further down that says:
> Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. > If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
But that's more a question of "when should I use context?". The entire purpose of context, as a tool, is to pass some value down to nested components without passing it as props .
Just my two cents on the article:
In a react app, I would refrain from using document.querySelector
as it is a side effect. You want to use Refs instead. Or add a note for the reader that you did this on purpose to keep things focused on the actual tutorial.
I would also add the reason for adding { passive: true }
to the event listener, since there is a big reason for this and that it would be a bad idea to blindly subscribe to the scroll
event without adding it.
You should never use this.state inside the setState functions as you can’t rely on its value at that point.
Prefer the following: this.setState((state, props) => ({ counter: state.counter + 1 }));
https://reactjs.org/docs/state-and-lifecycle.html See the “State Updates May Be Asynchronous” section
If you use a PureComponent
, it each should only change if their props change. So if the wrapping component gets new props that don't pass down to the child, only the wrapper will rerender.
https://reactjs.org/docs/react-api.html#reactpurecomponent
It only does a shallow comparison though, so if OP nests his props deeply in objects, they will have to use the shouldComponentUpdate
lifecycle method, but it would avoid rerenders on props that are not included or OP deems inconsequential to the child. Though it's generally a good practice to only pass props that are relevant to the receiving component.
I use react storybook as a library for my components, https://storybook.js.org
Currently the components are organized alphabetically as I'm not sure how to group them. You can also add style guide elements to your stories, for example check out lonely planet's storybook
I really like this! Super clean and I love the animations and detail that went into it. I second the routing comment that u/sjaigeo mentioned. React Router is a super popular routing solution for React, and it definitely will pay dividends to know how it works.
Another piece of advice I might give is to explore more state management solutions in React, because there are indeed many. Having a top level state object where you pass down props to your components is completely valid, and will definitely work for a smaller application, such as this. However, as the application expands, you might find that you run into an issue with prop drilling (passing down props through multiple levels of components). I'd try a few different state management solutions and see which one you like most. Definitely try using React's own Context API with useReducer and useState hooks to start. Once you feel comfortable with that, you can check out other solutions like Redux (not as dead as people might have you believe), MobX, or Recoil.
Also, Material UI is an absolute bear of a component library to work with. It's trying to do everything at once. If you're looking for a component library, I'd recommend something like reach UI (reach.tech), which is something a bit less heavy that you can customize yourself. Alternatively, you can play around with a more CSS oriented solution like Tailwind CSS (https://tailwindcss.com/), which is getting a lot of buzz right now.
Great job though! Always great to see mobile devs coming over to our neck of the woods to try out some web dev work.
I can personally vouch for Ryan Florance's course on Frontend Masters.
I would also recommend Dan Abramov's Redux course on egghead.io.
Dan and Ryan know what's up. (although I prefer browserify to webpack)
Sean and Mark are correct. React calls componentDidMount
/componentDidUpdate
synchronously after updating the DOM. If a state update is requested, React will synchronously process it as well (and commit its updates to the DOM). This all happens before React yields control back to the browser to layout and "paint" the update. So the intermediate state isn't actually visible to anyone.
It's more efficient to only update the DOM once of course, but some use cases require a second pass (e.g. measuring or positioning content that's just been rendered) so React supports this too.
(Note that reading certain DOM properties, like measurements, will force a synchronous layout by the browser, but this still won't be visible to the user. Painting will still wait until after scripting has completed.)
Edit here is a Code Sandbox that demonstrates the behavior we're discussing: https://codesandbox.io/s/o5543ljv15
It looks like you have posted a lot of code! If you are looking for help, you can improve your chances of being helped by putting up a minimal example of your code on either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new).
I am a robot, ^beep ^boop, please don't hurt me! For feedback or advice on how to improve this automod rule please ping /u/swyx.
I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/reactjs) if you have any questions or concerns.
> On top of the JS-like syntax, there’s the stuff that isn’t JS at all. Angular 1 had things like ng-repeat="item in items" and ng-click="doStuff()". Angular 2 switched it up a bit because people found the Angular directives confusing, so now it’s *ngFor="let item of items".
Angular 1 had a massive problem with confusing treatment of properties passed to directives, or in plain language, was it <mydirective param="{{foo}}"/>
or <mydirective param="foo"/>
? The new template syntax was designed pretty much to avoid issues around that.
To add to that, if you want to use the current state, provide a function that takes the current state:
this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
Taken from here: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly
No it's not deprecated. They recently added this method as a replacement for componentWillReceiveProps(). componentWillReceiveProps() will deprecate in v17.
From React documentation
>It is not recommended to use this lifecycle (componentWillReceiveProps) in the new code. If you need to calculate next state based on a change in props, use the static getDerivedStateFromProps lifecycle. If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead. For some use cases, you need to use both: getDerivedStateFromProps for a calculation, and componentDidUpdate for a side effect.
Deprecation notice on componentWillReceiveProps method.
>This lifecycle was previously named componentWillReceiveProps. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
> I didn't notice anything really changed on their main React website (https://reactjs.org/docs/hello-world.html) so I assume nothing is changed (so as long as I know about the conversion, I am good?)
I've been hearing for a while that the React team has been working on a massive overhaul of their docs but yea, nothing yet. I don't consult the docks much 😬 but often see complains that they can be outdated on certain subject matter.
babel-loader
is a bridge to integrate Babel into Webpack(to process files by mask you provide through Babel before bundling with Webpack).
Next, with "plain" Babel you will need to specify a lot of different plugins to get transformation you need.
You will (almost - until you use Preact or don't want to have JSX transformation and prefer React.createElement
instead) definitely need one or few plugins to process JSX for React. So you add @babel/preset-react
instead of cherry picking separate babel plugins and configuring them manually.
Finally, you will definitely want to have transformation for language feature that not supported by all your target browsers. Do you need a plugin for spread operator ...
or are target browsers all support it? Do you need polyfills for IE11? And what exactly? To solve this holistically we use @babel/preset-env
and specify target browsers in config instead of connecting bazillion plugins manually.
One disadvantage, at least on first load, is that a lot of boilerplate React code will have to be reloaded for each domain.
It might make more sense to use code-splitting to load code only as necessary. This is React's recommended approach.
If you want to use your filter state outside the component where it was defined, you generally should define that state in a parent component. See: https://reactjs.org/docs/lifting-state-up.html
You’re starting to get close to the point where you’ll see why solutions like Redux were created.
> - Abusing the key
property to make a component remount
This isn't an anti-pattern or abuse - this is actually the intended purpose, and a pattern that is recommended by the React team depending on what you're trying to do:
Yeah, I'd definitely say try/catch is your friend. Really your 'main' logic action should be wrapped in a try/catch no matter what, since this is the React subreddit, I think it's worth mentioning that this would commonly look like an error boundary at the top of your component tree.
If a hard error is hit, this error boundary component should catch it and do two things:
I usually include try/catch blocks through out my code if an error can happen outside of my control, and I want to control what happens within that component or part of the tree. For example, it's not like a failed network request for a resource should throw an error that bubbles all the way up to the error boundary, I'll just catch it, set some state in that catch that updates the render to let the user know what happened.
Whatever works for you, really.
It doesn't look like you've tried anything. If you want help, show what you've done and ask a specific question. Even better if you provide a link to a CodeSandbox which has a demo of the code that you are attempting.
I know you mentioned in your other post that you are working on proprietary code, so you can't post it, but with issues like this, it will be difficult to help without some kind of minimal reproduction steps.
I can tell you that the queries are working for me to find a select with an implicit listbox role.
Here is a working sandbox with that selector working: https://codesandbox.io/s/objective-colden-7p40u?file=/src/App.js
I'm wondering if this is still related to the test executing before the selects are on the window?
Would it be possible to create a very small version of whatever you are making in a codesandbox and share the link to that? The process of creating it may also help you find the issue.
That's the approach you would use in direct-dom-modification scenarios like backbone.js apps or freestyle jquery proejcts. But with react, that's going to be a pain.
React much prefers unidirectional data flow - https://facebook.github.io/flux/docs/in-depth-overview/#structure-and-data-flow while not react-specific, it nicely outlines the idea.
React components should ideally be just instructions on how to render data. That data gets fed into the top of react render tree, react then figures out what needs to be done to get dom into the state needed by the data. If data needs changing, components trigger events, usually referred to as actions. Event listener catches that, modifies the data as needed, feeds the new data into the render tree, triggering a re-render of the whole react render tree. That sounds insane when you're used to jquery, but due to the tech behind react the performance is good. And on the upside, you don't need to think how to modify the dom after this or that happens, all you have to outline is the "initial render" part, because every render is essentially initial render.
That data and event handler might be redux, or plain react state or context, or one of many other solutions. Just remember this - it should be okay for your react components to re-render whenever they want. As long as the same data is passed to them, the output should be the same.
As for your immediate issue of modifying something many levels up, https://reactjs.org/docs/context.html context would be an easy solution.
Yes! Look at the controlsadd-on. With controls you can play with the input props of a component to see what edge cases it can handle. This way, a designer can check if a component is available that fits the requirements of their new design.
You can even let testers/QA hook into Storybook and write tests for components through stories.
The developers should still make an effort to showcase all possible use cases of a component, so other developers/designers can check what is available. That way it really becomes a communication tool - more than just a simple style guide.
From the React docs:
> You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.
useMemoOne
provides useMemoOne
and useCallbackOne
which are drop in replacements for useMemo
and useCallback
that provide a semantic guarantee (stable cache) if you need it
Here's a free egghead course on learning express for node.
If you're familiar with js you'll find express easy to grok and work with.
or
None! Udemy doesn't care about copyright. It would be more ethical to torrent stuff than to buy them from Udemy.
You can find some alternative there (some for free): https://github.com/enaqx/awesome-react#video-tutorials
This is still my fav: https://egghead.io/series/react-fundamentals
I forked your blitz and updated the code. https://stackblitz.com/edit/gitclone-vod9r4
what I did was:
const [list, setList] = useState(0);
const [listData, setListData] = useState([]);
then passed the listData to your Card component.I was a bit in shock when I first heard it, but having the Firebase config public is not a security risk. Instead, you need to focus on having the appropriate security rules in place so that access is limited. The security rules are extremely flexible (dangerously so) and let you lock down access to data at any level. Check out the security documentation to learn more - the examples are pretty self explanatory.
This tutorial is pretty dated and is using the older version of the React Transition Group API. Here is how to do a simple fade-in/fade-out animation using the newer API + GSAP.
Edit: Yuck... Reddit's new inline code formatting is kind of shit... Here is a codesandbox that does what I'm doing here, but throws in a couple more GSAP related properties.
// Set a standard duration
const duration = 300;
// Initiate the animationconst animation = (target, dur) =>TweenMax.from(target, dur / 1000, {opacity: 0,height: 0});
// Create your component that has whatever is being transitionedclass AnimateIn extends Component {state = {entered: false};handleClick = () => {this.setState({ entered: !this.state.entered });};render() {return (<React.Fragment><button onClick={this.handleClick}>Show/Hide</button>{/*Add a transition Component, and use the followingprops to call the animation on both Enter and Exit*/}<Transitionin={this.state.entered}onEnter={node => {animation(node, duration);}}onExit={node => {animation(node, duration).reverse(0);}}mountOnEnterunmountOnExittimeout={duration}><div>Your Content Goes Here.</div></Transition></React.Fragment>);}}
While I don't think an outright merge would ever happen because big egos, the next best thing is for the projects to steal each others' great ideas until the projects are essentially the same.
For Flow, stealing Typescript's ideas hasn't gotten a lot of traction, unfortunately. For example, the Github issue to enable Flow to import the established TypeScript .d.ts has sat there since 2014 without an implementation (https://github.com/facebook/flow/issues/7).
But thankfully the TypeScript folks have had a lot more success at poaching the good stuff from the Flow ecosystem. For example, as of at version 2.4, TypeScript can infer types (so for example let x = 3 will set x to be a number). (https://www.typescriptlang.org/docs/handbook/type-inference.html). As I remember it, this was the one huge advantage that Flow had over TS when it first came out.
I'm not sure whether you're agreeing or disagreeing with the template syntax, but my intention was to say that it's not really better in Angular 2, it's just different. You have to re-learn a special syntax again.
I agree that the docs are a big part of the confusion, but it's also because there's like 15 different ways to do everything.
This right here is exactly what I'm talking about:
> ngFor is not a template expression. It’s a microsyntax...
So once I've internalized which parts of JS work inside a template expression, I need to learn this "microsyntax" too, and keep them straight in my head. Ugh.
And all the little callouts in red boxes are stumbling points in the abstraction or terminology that really should be tidied up. Like these little things:
> A template input variable is not the same as a template reference variable!
> Don’t make the mistake of writing ngIf="currentHero"!
> Do not put the asterisk (*) in front of ngSwitch. Use the property binding instead.
> Do put the asterisk (*) in front of ngSwitchWhen and ngSwitchDefault. For more information, see * and <template>.
What do you mean by "silence"? It's explicitly called out in "breaking changes":
https://reactjs.org/blog/2018/10/01/create-react-app-v2.html#breaking-changes
https://github.com/facebook/create-react-app/releases/tag/v2.0.3
If you don't see a lot of people complaining about it, it might mean that most people weren't upset by this change. In either case you're welcome to file an issue to express your concerns. The behavior was changed in response to people's concerns about the previous one. Maybe we can find something better still?
Then the question was wrong. Autofocus is part of the HTML5 spec and is supported in every browser.
render(){
return <input type="text" autofocus />
}
And you can't do anything "as soon as the component renders" when all you can use is componentDidUpdate
. The first render will always happen before componentDidUpdate
fires.
https://reactjs.org/docs/react-component.html#componentdidupdate
> componentDidUpdate()
is invoked immediately after updating occurs. This method is not called for the initial render.
No, it's being deprecated. Here's a post detailing alternatives: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
The initial reaction of many is to use the new method getDerivedStateFromProps, but that is often not the correct course of action. Here's a post explaining that: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
​
this.setState({ isWrong: true })
Use onClick event for button
<Button onClick={() => this.setState({ isWrong: true })} />
Tip: It would be more readable to call a function inside the component which calls this.setState
Well, to make your life easier. You should only use componentDidMount
. This is because react made componentWillMount
legacy. And it will probably be removed in or around react 17. So its best to avoid it altogether. :)
In React, you shouldn't be doing multiple levels of component inheritance - you should only ever extend React.Component
, which is an effectively empty base class. See the Composition vs Inheritance page in the docs.
Just use create-react-app. Everything is bundled and configured for you out of the box. https://reactjs.org/docs/add-react-to-a-new-app.htm
The React docs are very good.
Not particular to react, but I also enjoyed Dan Ambramov's redux egghead course
The only thing wrong with IRC is that it's plain and old. Sharing code snippets, integrations, bots that can actually do cool stuff, media, inline previews, video and audio, etc. Communication has evolved, IRC hasn't.
I'm loving the Slack + Speak combination and it really does feel like the IRC of the 21st century, but they're not open source. Rocket.Chat is, as is Mattermost, but it would be great if these (as well as Slack and Discourse) were all implementations of a standard protocol...