I've started to code my first React app and it's awesome, but I can't figure out how to manage css files per-component(so the actual CSS won't load if it is not necessary).
React with webpack(correct me if I'm wrong please) wraps the project in such a way that at every given moment the app loads only what it needs(in terms of JS).
So if I have my main App component with only two buttons visible: btn-01 and btn-02, and inside of this component I have another two: component-01 and component-02, and they are hidden till the corresponded button is clicked(btn-01 for component-01), these components won't be loaded until the actual button is clicked(am I getting this right?), however this is not the same with css as I can tell, because I see the css of each of these(component-01 and component-02) components loaded right away the App is loaded, even though none of the buttons are clicked.
I'm not a big fan of inline styling, but I did test it with css module, but the result is the same in this aspect. So I'm not even sure if this is possible to implement in an easy way.
Here's a code, so perhaps I'm not implementing it correctly, but please don't mind the none-DRY code etc.
So as you may see, the style of Component-01 and -02 are loaded even though there is no need for them at the moment(none of the button is pressed).
App.js
import React, { Component } from "react";
import "./App.css";
import Component_01 from "./Component-01/Component-01";
import Component_02 from "./Component-02/Component-02";
class App extends Component {
state = {
isComponent_01: false,
isComponent_02: false,
};
toggleComponent01 = () => {
this.setState({
isComponent_01: !this.state.isComponent_01,
});
};
toggleComponent02 = () => {
this.setState({
isComponent_02: !this.state.isComponent_02,
});
};
render() {
let showComponent_01 = null;
if (this.state.isComponent_01) {
showComponent_01 = <Component_01 />;
}
let showComponent_02 = null;
if (this.state.isComponent_02) {
showComponent_02 = <Component_02 />;
}
return (
<div className="App">
<button className="btn-01" onClick={this.toggleComponent01}>
Btn-01
</button>
<button className="btn-02" onClick={this.toggleComponent02}>
Btn-02
</button>
{showComponent_01}
{showComponent_02}
</div>
);
}
}
export default App;
Component-01.js (and Component-02.js, just with -02.js)
import React from "react";
import style from "./Component-01.module.css";
function App() {
return <div className={style["component-01"]}>Component-01</div>;
}
export default App;
Related
Trying next with layout pattern:
https://github.com/zeit/next.js/tree/canary/examples/layout-component
And the problem is that Layout component get remounted on every page change. I need to use layout component as a Container so it'll fetch data from server on every mount. How can I prevent layout to get re-mounted? Or am I missing something there?
This helped me for persistent layouts. The author puts together a function that wraps your page components in your Layout component and then passes that fetch function to your _app.js. This way the _app.js is actually the components that renders the Layout but you get to specify which pages use which layout (in case you have multiple layouts).
So you have the flexibility of having multiple layouts throughout your site but those pages that share the same layout will actually share the same layout component and it will not have to be remounted on navigation.
Here is the link to the full article
Persistent Layout Patterns in Next.js
Here are the important code snippets. A page and then _app.js
// /pages/account-settings/basic-information.js
import SiteLayout from '../../components/SiteLayout'
import AccountSettingsLayout from '../../components/AccountSettingsLayout'
const AccountSettingsBasicInformation = () => (
<div>{/* ... */}</div>
)
AccountSettingsBasicInformation.getLayout = page => (
<SiteLayout>
<AccountSettingsLayout>{page}</AccountSettingsLayout>
</SiteLayout>
)
export default AccountSettingsBasicInformation
// /pages/_app.js
import React from 'react'
import App from 'next/app'
class MyApp extends App {
render() {
const { Component, pageProps, router } = this.props
const getLayout = Component.getLayout || (page => page)
return getLayout(<Component {...pageProps}></Component>)
}
}
export default MyApp
If you put your Layout component inside page component it will be re-remounted on page navigation (page switch).
You can wrap your page component with your Layout component inside _app.js, it should prevent it from re-mounting.
Something like this:
// _app.js
import Layout from '../components/Layout';
class MyApp extends App {
static async getInitialProps(appContext) {
const appProps = await App.getInitialProps(appContext);
return {
...appProps,
};
}
render() {
const { Component, pageProps } = this.props;
return (
<Layout>
<Component {...pageProps} />
<Layout />
);
}
}
export default MyApp;
Also, make sure you replace all the to <Link href=""></Link>, notice that only have change the Html tag to link.
I struggled because with this for many days, although I was doing everything else correctly, these <a> tags were the culprit that was causing the _app.js remount on page change
Even though this is the topic Layout being mounted again and again, the root cause of this problem is that you have some data loaded in some child component which is getting fetched again and again.
After some fooling around, I found none of these problem is actually what Next.Js or SWR solves. The question, back to square one, is how to streamline a single copy of data to some child component.
Context
Use context as a example.
Config.js
import { createContext } from 'react'
export default createContext({})
_App.js
import Config from '../Config'
export default function App({ Component, pageProps }) {
return (
<Config.Provider value={{ user: { name: 'John' }}}>
<Component {...pageProps} />
</Config.Provider>
)
}
Avatar.js
import { useContext } from 'react'
import Config from '../Config'
function Avatar() {
const { user } = useContext(Config)
return (
<span>
{user.name}
</span>
)
}
export default Avatar
No matter how you mount and dismount, you won't end up with re-render, as long as the _app doesn't.
Writable
The above example is only dealing with readable. If it's writable, you can try to pass a state into context. setUser will take care the set in consumer.
<Provider value={useState({})} />
const [user, setUser] = useContext(Config)
setUser is "cached" and won't be updated. So we can use this function to reset the user anytime in child consumer.
There're other ways, ex. React Recoil. But more or less you are dealing with a state management system to send a copy (either value or function) to somewhere else without touching other nodes. I'll leave this as an answer, since even we solved Layout issue, this problem won't disappear. And if we solve this problem, we don't need to deal with Layout at all.
I'm trying to make React component that dynamically imports requested Material-UI icon,
when the page loads. My solution presented here works, but it gives warning
at compile time. Additionally it slows down the compilation of the project.
Any idea on how to do this properly?
https://github.com/jurepetrovic/ordermanager_demo
The main logic is found in App.js, lines 5-10:
import React, { Component } from 'react';
import BarChartIcon from '#material-ui/icons/BarChart';
const MaterialIcon = ({ icon }) => {
console.log("icon: " + icon);
let resolved = require(`#material-ui/icons/${icon}`).default;
return React.createElement(resolved);
}
class App extends Component {
render() {
return (
<div>
<MaterialIcon icon={"PowerSettingsNew"} />
</div>
);
}
}
export default App;
The warning it gives is this:
Compile warning
I finally found the simplest solution to this problem:
import all material icons from the package:
import * as Icons from '#material-ui/icons'
I assume you fetch your icon names from your api and finally you have something like this:
var iconNamesArray = ["FitnessCenter","LocalDrink","Straighten"]
Finally load your Icons like below:
<div className="my-icons-wrapper-css">
{
iconNamesArray.map((el,ind)=>{
let DynamicIcon = Icons[el]
return(
<DynamicIcon className="my-icon-css"/>
);
})
}
</div>
And your icons will appear in the screen.
When using Next.js, I want to show a modal based on a url, on top of another page.
If gallery.js is the page component, I want /gallery/image/1232132 to display a modal with an image, on top of the gallery page.
Is that possible?
This question is a bit old, but since March 2020 there's a full example on the official Next.js repo (you should probably use this since it must be the "recommended way" by the maintainers):
https://github.com/vercel/next.js/tree/canary/examples/with-route-as-modal
Here's the original issue:
https://github.com/vercel/next.js/issues/8023
And the related PR:
https://github.com/vercel/next.js/pull/11473
If I understand your question correctly you want to add deep links to the individual gallery items. This is possible, but you need a custom server to handle custom routes.
The first thing you need to do is setup the routes. I shared an example here: using React router with Next JS route.
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
routes
.add('gallery', '/gallery')
.add('gallery-item', '/gallery/image/:image', 'gallery')
Then you can access this parameter in the getInitialProps method, and render the modal if the image parameter is set:
import React from 'react';
import PropTypes from 'prop-types';
export default class Gallery extends React.Component {
static propTypes = {
image: PropTypes.string
};
static getInitialProps({query: {image}}) {
return {image};
}
render() {
const {image} = this.props;
return (
<div>
{image &&
// render modal
}
// render gallery
</div>
);
}
}
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.
import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
'./img/p1.png',
'./img/p1.png',
'./img/p1.png'
];
const Slideshow = () => {
return (
<Fade
images={images}
duration="5000"
transitionDuration="1000"/>
)
}
What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.
class App extends Component {
render() {
return (
<div className="App">
{Slideshow();}
</div>
);
}
}
export default App;
This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?
Nothing seems wrong in this code.
try defining Slideshow() function inside app component.
make a call like "{ this.Slideshow }".
Check by removing "./" in image path. (Try..)
Also check the path of image. Sometime they refer to public folder outside the src folder. maybe public/images/img.png
Slideshow is a React component, so you need to render it using JSX, not invoke the function:
class App extends Component {
render() {
return (
<div className="App">
<Slideshow/>
</div>
);
}
}
export default App;
Using Mobx, after updating the store (i.e. clicking the button) the component does not re-render. I've installed mobx devtools which shows nothing after the initial load, and there is no error in the console. Any ideas what I've done wrong?
Store.js:
import { observable } from 'mobx';
class Store {
#observable me;
constructor() {
this.me = 'hello';
}
change_me(){
this.me = 'test 1234';
}
}
export default Store;
layout.js:
import React from "react";
import { observer } from 'mobx-react';
#observer
export default class Layout extends React.Component{
render(){
return(
<div>
<h1>{this.props.store.me}</h1>
<button onClick={this.on_change}>Change</button>
</div>
)
}
on_change = () => {
this.props.store.change_me();
}
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import Layout from "./components/Layout";
import Store from "./Store";
import DevTools, { configureDevtool } from 'mobx-react-devtools';
// Any configurations are optional
configureDevtool({
// Turn on logging changes button programmatically:
logEnabled: true,
// Turn off displaying conponents' updates button programmatically:
updatesEnabled: false,
// Log only changes of type `reaction`
// (only affects top-level messages in console, not inside groups)
logFilter: change => change.type === 'reaction',
});
const app = document.getElementById('app');
const store = new Store();
ReactDOM.render(
<div>
<Layout store={store} />
<DevTools />
</div>
, app);
I would start by adding #action to your change_me() function. From what I understand, it's not always completely required, but I have encountered problems like this in my own code several times when I've forgotten to add it.
Additionally post your .babelrc as #mweststrate suggested, as it will help others to check that the proper plugins are loaded.
Just add makeObservable(this); in constructor function like below
constructor() {
makeObservable(this);
}
My guess would be to have uninitialized #observable. It is very counter-intuitive, but Babel doesn't handle those well. Even adding #observable me = undefined might help (see the generated js code when you assign something there. Generally I'd remove constructor completely and move the initialization to declaration (i.e. #observable me = "hello" an no constructor). It should then work fine.
Watch the binding of the this context.
<button onClick={this.on_change}>Change</button>
the this reference will not be to the class, so likely when you are actually clicking it is going to say something along the lines of no props on undefined. Changing to:
<button onClick={this.on_change.bind(this)}>Change</button>
should fix it. Or better yet, bind the context in the constructor so its not re-binding on every render
constructor(props) {
super(props)
this.on_change = this.on_change.bind(this)
}
then you can go back to your