Yeah, that's a fair question, I should've provided a solution rather than just criticizing. Here's something that I think is a better solution:
https://codesandbox.io/s/hash-navigation-919fp?file=/index.html
It uses the :target
CSS tag to tell if an ID is being targeted, and will only show that element. This is more accessible, uses semantic HTML tags, and allows for link sharing.
I'm a bit busy right now to contribute a PR, but that example should give you a demo of what I'm thinking of.
A quick performance check. https://codesandbox.io/s/awesome-jones-2fpy1?file=/src/index.js
long hand: 0.12499996228143573 short hand 1: 0.7600000244565308 short hand 2: 0.1700000138953328
Long hand is faster because you don't need to waste time and memory space building an array. Premature optimization is the root of all evil. Just keep things simple.
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;
Vue is totally worth learning because there's less to learn than the alternatives.
Angular has an ocean of modules, declarations, providers, services etc. that suit itself better to enterprise systems interfaces. React is pretty simple on its face but gets kinda ridiculous once you realize project structure, class conventions, store/context APIs, are all over the place and everybody's "best practices" are so different that reading others' JSX becomes a game of sudoku. IMO, Vue minimizes all of this by drawing lines in the sand like where you should write markup vs computation.
BTW, if you don't wan't to download the dependencies, lemme also rep codesandbox for having the best prototyping experience on the block.
Thimble is great for simple and fast prototyping etc. Used it a few years ago. Best thing is that you don't have to make all of your stuff public without paying money but some cool features are missing.
If you introduce them to React in 8th grade, show them https://codesandbox.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
New tab/about:blank/google.com if it's just to play around in DevTools.
I really like https://codesandbox.io/ for more involved experiments, and it makes it easy to share them with team mates.
It's more like a performance test really, each "particle" is actually a React component, just to see how far it can go. Makes for a cool effect anyway. Full code: https://codesandbox.io/embed/387z7o2zrq
>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.
Oh man, you're gonna love this then!
Sandbox.io is basically Codepen with a folder structure and build process. It's sluggish at times but an overall better experience imo. Because it revolves around Webpack, you can skip that whole prototype-to-commit conversion process entirely for a component.
A very basic attenuation cone is calculated by using the dot product of the light position and each vertex in a vertex shader. Then, just blend two textures based off that mask!
Sure, you can install with npm install
command as stated in the docs. ( Vue3 docs, VueJS2 docs )
If you just want to try it out, you can also use CDN setup. Check out this working example to see it in action.
If you have any questions feel free to ask, I'll be happy to help :)
It's in the linked github repo. It's using react-flip-toolkit which is personally my favorite React animation library. Here's the demo.
Als Grundlage habe ich die Fragen/Antworten vom Voteswiper genommen, welche netterweise in einem guten Formatt zu finden sind.
Hier ist der Quellcode für die Visualisierung
You can just use pseudo-elements and rotate them with a transform: https://codesandbox.io/s/epic-thompson-ivswq?file=/index.html
Although an SVG as background would probably be better.
A very basic attenuation cone is calculated by using the dot product of the light position and each vertex in a vertex shader. Then, just blend two textures based off that mask!
Code: https://codesandbox.io/s/priceless-bohr-xlum2
PS: Rotation is backward, oops
I've spent a few days building an app demo on codesandbox. It was basically something to give me chance to practice Typescript (using React) on, but I thought I'd try to make something that people here might be interested in.
https://codesandbox.io/s/dae-211ii?file=/src/App.tsx
The basic idea is that we ask/answer quick, questions about ourselves, and then get shown the data from user answers along with a comments section. My thinking is:
​
Also, if anyone familiar with Typescript could have a look at my code and give me any pointers then that would be really appreciated. Thanks!
I think it would be more idiomatic if you did more of what you're doing for ProfilePicture
, PreviousWeek
, NextWeek
, and Clap
.
Currently, the code is currently largely up as a bunch of <div>
elements with classes. That's not wrong, but with React (or any component-based framework), it's usually better to think of things in terms of what they mean, create components for those things, then render the HTML in the place it makes sense.
I put together a CodeSandbox showing what this might look like in this case: https://codesandbox.io/s/0q9mrnq2jl?module=%2Fsrc%2FHome.js
Notice that although there's a lot more boilerplate, the actual structure of Home
is a lot clearer. We could also reuse a bunch of the components -- e.g. Content
, LeftSide
, RightSide
, CardList
, Card
-- on different pages without having to write new styles for them every time.
For this example, styled components probably is overcomplicated, but as your site gets bigger, and you have more components that need to be reused across the site, it can come in handy.
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.
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.
They don't, I have no idea how did you get that behavior but regular dollar sign is being displayed just fine in chrome: https://codesandbox.io/s/cocky-lumiere-b3mcj?file=/index.html
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.
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>);}}
A very basic attenuation cone is calculated by using the dot product of the light position and each vertex in a vertex shader. Then, just blend two textures based off that mask!
Something weird is happening and it's difficult to tell without seeing your code.
Things that may be causing this:
Here's an example of what it sounds like you're trying to do without any flickering, if it helps.
This is a simple mistake as are all bugs that take days to find :). You are currently trying to selectAll("rect")
in your update function when it should be select("rect")
. This matters because the selectAll
call will create a new grouping and therefore your databinding will be messed up whereas the select
will carry over the existing databinding.
The way I confirmed this (for future reference) was by printing out what grouping the update function returned for the update.selectAll("rect")
and comparing that against the data being passed in. They didn't match originally which led me to remember the select
vs selectAll
difference.
Here is an updated link to your example with it working. Hope that helps!
erm, yes? In the same way as you have to create a new app every time you want to develop something.
If you're just experimenting you could consider codesandbox which lives you a very light, online way to develop.
Hello my friend and welcome to using React!
What you are looking for is a piece of state that when toggled controls the className of two elements - the button that has been clicked, and an overlay that you want to appear when clicking.
You can achieve this by only applying a className when a part of the state is equal to true. An easy way to achieve this is using the "classnames" package.
I have set up a little demo for you here: https://codesandbox.io/s/z29yzyr604
Hopefully this helps you on your way :)
Why just not to use external state manager for storing data> React for view, state manager for data. And i think there will be no such problem. For example i recreated example app using effector: https://codesandbox.io/s/react-forget-itqmj?file=/src/todo/TodoList.jsx
No memo, no useCallback
you could create your own custom HOC
function withLocation(Child) { return function withRouter(props) { const location = useLocation(); // other relevant props // ... return <Child {...props} location={location} />; }; }
https://github.com/remix-run/react-router/issues/7256
https://codesandbox.io/s/react-router-v6-forked-132kc?file=/src/App.js
(TL;DR here is a working example for a possible solution)
Directly, that is impossible for the reasons you yourself outlined - @click="componentMethod"
is only possible in component templates, so compilation is mandatory. That means there are 2 possibilities:
sanitize-html
)Here is an example of a simple "bound-html" directive on CodeSandbox. Couple of notes:
innerHtml
click
at the moment@click
isn't a valid attribute so it cannot be in the html content (it isn't strictly speaking a template). You can:
@foo
to x-bound-foo
before setting innerHtml
The issue here is thingA and thingB are dependencies of that callback. So they should be included in the dependency array.
In this instance it would be safe to do that but react will yell at you (if you're using CRA)
the reason you shouldn't do that is react just ignores whatever function you pass into use effect on the renders where no dependencies change. So the old function is still hanging on the the state/closure values at the time of the last dependency change.
This is probably only a problem when doing asynchronous stuff in an effect.
I made a codesandbox to highlight the issue here:
https://codesandbox.io/s/old-firefly-pjh5v?file=/src/App.js
The role was specifically for the front-end. It was a very simple test on codesandbox.io that basically test whether I knew the basics of react (js library for building ui). The job expected me to know html/css/js like any other front-end role.
I was only expected to know how the front-end interacts with the back-end, not the specifics of how the back-end is implemented, thus any specific knowledge of back-end programming language wasn't necessary.
Ok so first, a CodeSandbox is 1000x more useful than a snippet! I took the liberty of creating one for you with the code you have above, and I filled in the `Search` component using a simple input box for now.
​
https://codesandbox.io/embed/strange-microservice-lmy3h
​
Second, so your events are kind of all over the place. List is rendered with an onChange prop but the component accepts onClick; and the two don't seem to mean the same thing. You are never handling the value received from Search in onChange, in other words you are never calling setSearch anywhere so that the new 'value' is passed into 'Search' (it IS a controlled component, it seems? That's why you have value and onChange).
​
Go ahead and use that Codesandbox above and try to give it a shot at what you're trying to do. I'll hang around to see if I can help, feel free to hit me up on the chat.
You should wrap the `TextInput` in a styled `View` instead of directly applying the styles to the `TextInput`.
The required text is just conditionally rendering a `Text` Component based on the length of the correlating string in state.
​
Like college math or elementary math?
I only gave 3 basic questions in a recent interview I gave hiring a junior, followed by a real-world pair programming exercise – questions here. The 3x questions took ~15 minutes for the candidate we picked (took me <5 minutes) and the pair programming took like 50 minutes.
To a Senior, I would give questions that make you think a lot more – eg. complex sorting and performant iterations over difficult data sets – but math isn't necessarily a part of it.
Honestly, as a Senior / Lead, it's been several years since I did any actual math beyond an elementary level at work – and I work on a financial product..
Either they're giving you stupidly complex questions or you're having difficulties doing basic math while doing interview questions. Neither are particularly your fault and a test of 45 questions seems excessively stupid – did they give you a HackerRank test or something?
Did someone sit with you during the test or was this just solo? From a hiring standpoint, they will not be able to learn anything about you or how you learn by simply seeing your answers – they will only see where you are now, not where you will go. If this is a first-round, remote test to weed out a few hundred candidates, I guess I can understand (I wouldn't do it).
They're likely just bad at interviewing/hiring, which is very common if not the norm.
It's still 50 key/value pairs but they don't have to be statically defined in your code necessarily, I put together a simple code sandbox demonstrating a working version.
Screenshots sound like a great idea. Better demos are being worked on. This demo is interactive and can move around the blue rectangle with WASD.
I avoid nested ternaries at all costs, so it would be option 1 for me, but then I also avoid reduce() wherever possible, so I might not be the best person to answer this.
I factor the intuitive nature and maintainability into my definition of "good" code over shortness, so while a one-line solution might be cool, I'll almost always spell it out so "future me" can fix it easier when it needs fixing.
Edit: I didn't actually say anything helpful here! Here's a codesandbox with a couple of alternatives: https://codesandbox.io/s/dank-voice-otr7e?file=/src/reduce.js
Option 3 - Use JS's falsey logic to turn undefined
s into 0
Option 4 - If you have lodash already, let a well-tested library do the work for you
So i tried making a codeSandBox for this, it seems to be working for me atleast, the video size is only 2mb so the loading time is so small, if you refresh the view of the sandbox you would see the loading text for a bit and everything else would load with the video, i tried the onPlay and onLoadedData events and both are behaving as expected your milage may be diffrent though as your video is larger
https://codesandbox.io/s/nice-currying-q11cp?file=/src/App.js
My fav so far, and easiest to play with, is the new `startTransition` API.
No more setTimeout hacks to tell React something can wait. You can *see* the difference, that was impressive.
I used a random walk to create an evil example. Works but laggy 👉https://codesandbox.io/s/react-17-random-walk-vpwlx
Same code with a startTransition and the new rendering – fantastique
Input no longer lags and you can see the random walk is getting debounced as evilness intensifies.
No, you can't. A component that changes state will always rerender. As somone else mentioned, you can use `React.memo` (or shouldComponentUpdate) on the child components to prevent them getting rerendered if they don't need.
However, something not quite known is that react doesn't re-render a part of the tree if that tree keeps the same reference on rerender.
This is useful when passing elements through children props (in the scenario where you have 3 components: Parent, middle and child - The middle can update state getting rerendered, but if the child is just a prop passed from the parent, the child won't get rerendered because it's the same reference.
But this also means that you can wrap your element into a useMemo
and it won't rerender unless useMemo's dependency keys change (re-evaluating the memoized value). Example sandbox here: https://codesandbox.io/s/determined-hodgkin-tobo9?file=/src/App.tsx:0-636
These days, you can really jazz up website as much as you'd like. These days, if anything, you gotta learn to constrain yourself. By all means go nuts when you're making a portfolio website, since you want to impress really impress the viewer, but for everyday use, don't go too nuts. It gets tiring on the eyes.
If you really want to go crazy with the CSS just for showing things off, you can create jsfiddle.net or codesandbox.io portfolio that shows off individual small projects.
One thing to note if you're going to enter - the 'rules', such as they are, state that after making a component you must "Adapt it to the Atomize requirements following the example". Those requirements are not stated anywhere, even in the Atomize repo which isn't linked from the contest. That means that Quarkly could disqualify any entry they want to just "because it doesn't meet the requirements."
Enter at your own risk.
Also, Quarkly copied their user agreement from https://boardcrm.io/agreement and just changed the company name. Maybe they have permission to do that, but it looks dodgy to me.
Take this result with a grain of salt - it will only give you performance boost, up to a point, when the components are used as leaf components; if they do render more components themselves the performance gain is smaller or even plain old worse than statefull components.
See benchmarks at:
simple tree - https://codesandbox.io/s/q9llr1p2w9
complex tree - https://codesandbox.io/s/0qzz2nwjl
Open the console to view results.
i am not going to help you because i want to encourage more specific questions. dont expect people to guess what issues you need help on, ask specific questions. also link to codesandbox is much better than just a plain github. you can import from github like this: https://codesandbox.io/s/github/harshmanwani/receipt-tracker
please put more effort to help people help you.
So what you want to do is use the CardList component to render a Card for each item. That means you need to import the data in to CardList, and then map over that data, rendering a Card for each item. You can give each Card the information it needs with props.
I've forked your sandbox here with some comments https://codesandbox.io/s/mmr2ypy129
Also note you don't need to import ReactDOM
What does the parent component code look like when you're passing down 'X' as a prop?
It would help if you could post the complete code as a Github gist (or even better, as a CodeSandbox.io project ).
Okay there are a few things going on here that look a little funky.
First App.js is not an HOC / Higher Order Component it is just a regular stateful component. Also I don't think you need context just yet you only need to pass props one layer deep. So this can simply be resolved by formatting your components a little differently.
That being said it looks very unlikely that you actually need an App.js. All it is doing is rendering the Body.js component. Body.js contains the logic of the app which is good and it renders children that is great so far. What we should do is remove App component from RouterSetup and replace it with Body component instead. Then from there your best bet is to move the Route component out of RouterSetup and into the Body Component So your body component would looks like this.
<div className="App">
<NavBar />
<AddStudentForm
studentLength={this.state.students.length}
fetchStudentsFromParent={this.fetchStudentList}
/>
<Route exact to="/" render={() => <Home studentLength={this.state.students.length} />} />
</div>
Notice that I am using the render prop for the route instead of the component prop this allows us to pass props to the underlying component.
I made a codesandbox below that can kind of demonstrate what I am talking about. I tried to map it similar to your projects you can find the core of the logic in the '/layouts/App.js' file
There's a bunch of demos actually, both the API and examples.
The one closest to what you describe would be the "Typical Component" demo:
There are 3 demos in that section; the Pathify approach, and two vanilla Vuex approaches (which have a LOT more code).
Let me know if that's what you're talking about, otherwise, perhaps the demo availability should be made clearer?
If you want an actual ide there's stuff like cloud9.
Otherwise for simpler things:
https://codesandbox.io/ - Highly recommended. You can do just about anything JS related with this.
With simple local only state you can get away with recompose's withState HOC.
https://codesandbox.io/s/n5MYV54KW - Almost straight from recompose's examples
ReactCasts#11 - Recompose youtu.be explains more.
Sure thing!
Actually I do have one suggestion. It would be awesome to be able to link to a specific file and even line number so I can direct the reader to the appropriate spot when clicking on the "Edit on CodeSandbox" from an embed. You could take a page from Gist and do something like https://codesandbox.io/s/[id]#file-[filename]-L[linenumber].
This would allow me to link to specific areas of the code as I'm writing up a tutorial or post.
It would appear that the way I am setting the <Card /> component array is the problem. So maybe there is a different pattern here that I should be following.
What do you mean? I threw this in a BS5 codesandbox.io and it looks exactly as expected.
Could you please provide a screenshot and a more detailed explanation of how the result of this code differs from what you expect?
Obligatory not-sure-if-this-is-an-anti-pattern or if there's other issues that may come into play here, but just re-exporting the home page like this example and tying in the same alias as in your example also works if you really don't like query params. Does seem to be less performant in general though since you're duplicating pages and causing full routing events when opening / closing modal, could be an issue.
You were doing some pretty weird shit there, so I redid your whole thing:
https://codesandbox.io/s/cocky-hugle-4t5t2?file=/src/App.js
Let me know if any of the stuff that I removed was a hard requirement, and we'll try to figure out how we can keep it.
Your issue is this: all of your Card
s are depending on the same piece of state to determine whether they were clicked! When you configure your initial state in stores.js
, you create only a single boolean, clicked
:
const initialState = { clicked: false };
Then, you define a single action, handlerBuy
, that sets clicked
to true:
const selectedSlice = createSlice({
name: "selected",
initialState,
reducers: {
handlerBuy(state) {
state.clicked = true;
}
}
});
Then finally, in Card.js
, you pull in the value of clicked
from the Redux state to your local variable click
, and define a handler clickHandler
which dispatches handlerBuy
:
const click = useSelector((state) => state.clicked);
const clickHandler = () => {
dispatch(selectedAction.handlerBuy());
};
As such, here's what your code is doing: You've told all Card
s to determine whether they are clicked based on the same piece of global Redux state, and all Card
s to call the same handler to update that piece of state when clicked.
If you want each card to determine whether they've been clicked separately, then you'll need the shape of the data in your Redux store to reflect that, and the action you dispatch to reflect that as well. They'd need to keep track of something unique to each Card
. So, perhaps you could use your Card
's id
for that purpose? Instead of clicked
being a boolean, it could be an array of string
s representing the id
s of all cards that have been clicked. Then, handlerBuy
would instead take a string
id
as an argument, and add that id
to the clicked
array. Finally, in Card
, you'd need each Card
to check if their id
were included in the clicked
array. If you tried that approach, you'd end up with something like this. Does that help?
Downshift - fully customizable, I tried it to avoid styled components too. It requires much more code to write, here a lot of examples in "downshift" folder I hope will help you
There's a lot going on here and you're going to have to make a few changes before this is going to do what you want.
Here's a fully annotated example of what you're trying to do.
There's a few things to note here:
useState
and useEffect
.Please review this, google around and come back here with any questions you have 👍
You probably have something else going on. AFAIK a state change doesn't trigger a re-fetch for an a child img
tag. (see this codesandbox for example).
Could you give us a code sample?
Had a question regarding Material UI's table with sorting example. From my understanding, this line (in 'demo.tsx' file on line 83):
return a[1] - b[1]
ensures equal values keep the same order when sorting. But, isn't this always going to return 1, since the index of 'a' is always the index of 'b' plus 1? Why not just return 1?
Sure! Just don't use any npm
packages 😜
In all seriousness, though, you'll spend far more time getting Linux to work than you will being able to code (unless you're already a Linux pro). So rather just code online--use CodeSandbox, repl.it, or maybe GitPod.
Good luck!
Don't use a onClick function in a <li/> tag, this isn't a good practice. Instead go for a <button /> inside your <li/>.
You can see a example here: https://codesandbox.io/s/reddit-li-list-example-91rkj?file=/src/App.js
I tried to reproduce your described problem but it impossible, because your code doesn't runnable and you miss css styles for the modal component.
Can you make the example in https://codesandbox.io/ or other tools for interactive code demo?
I also looked into u/foldingaces's comment of React.StrictMode
issue.
More info on double render: https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/
In this demo, https://codesandbox.io/s/reactstrictmode-double-render-generates-different-unique-class-names-l7g64, double render will go away if you remove React.StrictMode
but will see two classes (if you had used your own code).
You can mitigate the issue by keeping the unique class name in the closure (move it outside return function
) and use it again (though it'd be added again in StrictMode).
const styled = (Tag) => (styles) => { const uniqueClassName = comeUpWithUniqueClassName();
return function NewComponent(props) { createAndInjectCSSClass(uniqueClassName, styles); return <Tag {...props} className={uniqueClassName} />; }; };
This is the most basic approach
<template>
<div class="columns">
<div v-for="n in 5" :key="n" @click="toggleImage(n)">
<img src="https://www.fillmurray.com/150/150">
<div v-if="isSelected(n)">Look at me</div>
</div>
</div>
</template>
<script>
export default {
name: "App",
data(){
return {
selectedImages: []
}
},
methods: {
toggleImage(n){
if(this.isSelected(n)){
const index = this.selectedImages.indexOf(n)
this.selectedImages.splice(index, 1)
} else {
this.selectedImages.push(n)
}
},
isSelected(n){
return this.selectedImages.includes(n)
}
}
};
</script>
The natural progression will be to extract image into a separate component and keep its toggled state internally
When I see that, I immediately think of the AnimateSharedLayout
behavior of Framer Motion, specifically as demonstrated in this example. All you need to do is conditionally render a motion.div
with the white border in each respective point on the credit card, and make sure they have the same value for the layoutId
prop.
Here is the documentation page: Framer Motion API | AnimateSharedLayout
Here's a quick example on how to achieve that:
> https://codesandbox.io/s/eloquent-cdn-jyojw?file=/src/App.js
It uses a prop to lay the options but if none is provided it will use a default.
Is something like this what you had in mind?
https://codesandbox.io/s/inspiring-hoover-no79w
I know there's a simpler way to do it but it's all I could come up with this early on a Saturday.
I've been working on a simple, lightweight, and blazing-fast UI library called Fluid. It's under 1.5 KB minified and gzipped.
Essentially, it is powered by a concept relatively similar to that of lit-HTML, but it has more refined update system, making it slightly faster.
Try it out on CodeSandbox, or take a look at the benchmarks.
You have the value on the input set to "HI". Take it out and you should be able to edit the input box. Check it out here: https://codesandbox.io/s/fervent-monad-y8nng?file=/src/App.js
You're close but what you just described is not quite accurate. Check out this example:
https://codesandbox.io/s/zen-drake-3xj8n
React does not fire the alert()
because it doesn't try to render the child component when condition
is false.
The actual issue is this:
<If condition={!!item}>{item.name}</If>
This will throw an error if item
is falsy because React will evaluate item.name
and pass it to If
as children
.
When you submit a new name, you're not updating isRadio
, so the old value (with the old name) is kept until a radio button is clicked to update it.
Since your employee name always appears in front of the selected option, I would suggest removing it from options entirely, and rendering it with the option / isRadio inside <Options />
. Like:
https://codesandbox.io/s/employees-experiment-v17-stable-forked-npett?file=/src/App.js
Here's a working example for you:https://codesandbox.io/s/distracted-kowalevski-78pev?file=/App.svelte
All vanilla CSS, not even SCSS. Nevertheless I'd highly advise you go with SCSS if and when possible. Svelte transitions are cool but I usually try to differentiate interactions and visuals as much as I can. For example I'd always opt-in for Svelte transitions where CSS transitions are simply not possible (e.g. route change). This example is far too simple for anything else than basic CSS.
If you do decide that it's worth the bundle size hit for using the Apollo, give Apollo Elements a try, it supports Vue quite well.
Live Demo of Apollo Elements in Vue
Some advantages over Fetch calls:
- declarative components
- cache normalized results
- if one query fetches user(id: 1) { id name picture }
, other queries can use that data without refetching
- local state management
- use components across frameworks
Hey again thanks for the reply, the default paragraph component doesn't support tab indentation. But the whole point of this library is that it is powerful and expressive enough that it will be easy to quickly implement something that fits your need.
I created a quick sandbox to implement what you asked for https://codesandbox.io/s/relaxed-albattani-x288z . Let me know if it makes sense.
You can add a class to the selected state of a MenuItem using the classes object prop! https://material-ui.com/customization/components/#overriding-styles-with-classes For example:
<MenuItem classes={{ selected: classes.selected }} value={10}>
Ten
</MenuItem>
Demo: https://codesandbox.io/s/material-demo-forked-jgijg?file=/demo.js
Hi, Thanks for checking out the library!
I'd like to clarify a few points:
​
> Why do you describe this solution as reactive?
Components react to it when you mutate the state. That is why the state is reactive. Things like RXjs are not the only thing you can call Reactive. Even simple callback functions are reactive. There's a great talk about this by Evan You, Creator of Vue.js
​
> Also... I don't understand why is it global? As I see, you create the state inside a component
You don't declare the global state in component, you actually declare the global state in your main index.js file before rendering the App. Here is an example .
I get why you might have thought of it like that because I put the code of creating the global State and using it in a component next to each other. I'll update the readme to make this a bit more clearer.
This global state is available on window.radioactiveStore.state. I am not using context API. This lets us mutate the state from the console and it will directly update UI, as shown here readme
​
> it seems like this is a useState in steroids
radioactive-store's state is fundamentally different from useState, in case of useState whenever you want to update the state, you have to create a whole new state and then manually set the new State. but in the case of radiaoctive-store's state No new state is created at all. Mutation is detected on state, component's that are dependent on part of state are re-rendered ( subscription model )
​
> I also found an issue
Thank you so much for reporting this bug! I'll work on this and try to find a workaround for it.
It sounds like you don't fundamentally understand React then. It's not doing anything special if you really understand the underlying language and web ecosystem.
But let's take a few lines of your code.
It looks like you are trying to do several fancy things at the same time, probably in response to some other issue you had that you were trying to fix. This results in code which is hard to understand because everything is now interdependent and there are no separation of concerns.
Start with a simple example of a working solution and build up from there.
Thanks! It uses History API by default, but this can easily be customized to support hash-based routing:
https://codesandbox.io/s/wouter-demo-hash-based-hook-5fp9g
The code size was essential, so I've decided not to include this in the library. I do plan to release hash-based hook as a separate package soon though.
Great technique, is just that I would prefer if you stick to the docs:
>useImperativeHandle should be used with forwardRef
I understand you're forwarding a ref in your demo, but if you could mention this it would be great.
I made a quick demo with the technique you're sharing + forwardRef
and I'm in awe with the possibilities.
https://codesandbox.io/s/naughty-currying-mmjc1?file=/src/User.js
I'm not sure about that, you may be thinking of Microsoft's own Visual Studio Codespaces / Visual Studio Online product. This appears to be just the containerized IDE connected to a specific repo. To me, this seems more akin to something like repl.it or codesandbox.io.
>you need to read the docs to replicate something that was once as easy as defining a method with the name componentWillUnmount
if you stop thinking in lifecycles then it's just "my component has two side effects and a memoization", as in: you express what's actually happening instead of routing everything through arbitrary constructs. but as long as you hang on, it's gonna be rough.
this example: https://codesandbox.io/s/26mjowzpr
hooks: a linear order of tasks, one building the foundation for the other.
classes: a nested soup 5 stages deep, implicitely injecting props into a void - hopefully something catches em in the end. some stages in the middle need pass through and catch results in "DidUpdate" but then what. hocs dissolve all discernible meaning.
IMO defining a function to return the initial state and obtain its type by `ReturnType<>` is a bit ambiguous.
Try typing everything as explicit as you can.
This is my try: https://codesandbox.io/s/react-context-usestate-501oq
I pasted this in a code sandbox to try it out. This works for me: https://codesandbox.io/s/determined-mcnulty-rvp6t. I think you were just missing binding the showOptions
method in the constructor. You could also make showOptions an arrow function and it would work as well.
Hello, I'm the creator of vee-validate. I suggest that you take a look at ValidationProvider component introduced in 2.1
which addresses a lot of issues where the directive falls short.
The idea that you create a new component called VTextFieldWithValidation
, feel free to shorten that name. Which is ValidationProvider
wrapping the VTextField
. This allows you to drop one-liner for each field and they would work seamlessly. For example, you could pass a name
prop to both the provider and the VTextField
.
I have an example for Vuetify over here. Take note that I illustrate both a refactored form and non-refactored form versions to showcase the difference.
With a v-for
and component :is
binding you could get a simple form generator working. I suggest using validation components from now on as the directive is becoming very limited.
Or an online sandbox with pre-fab projects you start, like https://codesandbox.io ? That way students start by creating a GitHub account, and just with that they're already a step ahead.
Here is a small demo sandbox: https://codesandbox.io/s/kkw61p4lno
It served me pretty well in understanding how react router works and was a good test-bed for my contributions back to RR. And most of the features and changes I made to the API where from suggestions and pending implementations for react-router(-dom). Such has hooks, the rework of Route
and the addition of Match
. So I really mean the title.
I'd greatly appreciate some feedback. Especially on merge of NavLink
into Link
and my style of documentation: https://github.com/StringEpsilon/Alnilam/tree/master/docs
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.
Synchronous re-rendering will happen whenever a component calls setState
from within componentDidMount
or componentDidUpdate
(or a setState
callback function).
Here's an example that shows what I'm talking about: https://codesandbox.io/s/o5543ljv15
Either ReactTransitionGroup or something like this, which is probably a bit easier to handle than messing with a bunch of classes. Comes in handy for all sorts of things, routes for instance: https://codesandbox.io/embed/r7qqnqq8x4
I answered a similar query where someone was using classes and mutable state for their game. The solution I advised was the Mobx library and I made a quick example:
If you are using OOP classes to represent and update your game objects, then a good fit for you would be Mobx. Basically it will let your react components observe your game state and refresh automatically when it changes.
Without it, you will have to manually tell React to refresh the UI when data changes, as you can't really utilise this.setState() when your state isn't a plain js object.
Quick example: https://codesandbox.io/s/wnlm07963w
Tell me if you find this helpful or if it's not really what you need : https://codesandbox.io/s/2v5jyr8orr
(I chose to store each creation function in the corresponding component, but you could as well extract it in a JS file or whatever. You can't put them in ModalRenderer because it's a state-less component (unless you switch to a stateful component)
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.
The consumer fires on all changes to the central store/provider, it is not like mapStateToProps at all. Worse, the provider renders all contents on any change. You can theoretically "pick state" but that involves rather complex juggling of PureComponent's.
Context is a low level api, if you wanted redux like functionality (like picking state and binding it to components that only render when their pick changes) then you need to write some not so trivial boilerplate around it: https://codesandbox.io/s/52jv4pw3rn And that just gives you connect in context. And notice how you're still writing actions and reducers.
Not too sure if this is what you wanted:
https://codesandbox.io/s/o97qznky8q
I borrowed Semantic's CSS.
The trick is to render all the child components but to use CSS to hide them.
This is a great answer.
If you're willing to use babel to enable some futuristic features, you can do stuff like this:
https://codesandbox.io/s/n4k7wy45mj
I've made a few changes to the example above - not all of them better but they show other ways round it. Principally:
const { active } = this.state
) at the top of the render method helps you keep track of what properties of the state you are using elsewhereI think a really important point here is that in your examples, you are assuming that something has already created the elements and you are modifying them based on your application state.
In React that idea is turned upside down - you are creating the elements using the state and props.
Happy coding!
Context is a low level api, if you want a redux-like store you'll have to add some minor boilerplate: preventing the main store from rendering contents on changes and wrapping PureComponents with just their state-pick into Consumers to prevent them from rendering on changes that don't concern them.
Here's an example that mimics Reduxes connect using plain context, but as you see this isn't looking too good: https://gist.github.com/drcmda/e71c10a1e2e45f73ef2e9b10e62f1c48
And here's the same with a little more comfort, this could work: https://gist.github.com/drcmda/db7d8fd924bf39620533a0419fba08fc (live demo)
You'll still have to write reducers, actions on so on. Personally i would recommend redux for app state.