When developing my project, I look at others for an example. When I looking at Instagram website. I see the class name of html is change when user is login. May I know how to achieve that actually? As what I know, react only live in one of the div in html structure.
// This code will render a component in the html root.
ReactDOM.render(<App />, document.getElementById('root'));
// But how to serve a whole new html file in react
How to serve a whole new html file in react? Is it violate the concept of react?
HTML and Document body are outside the React realm of DOM handling. So you can use good old querySelector for setting the class names.
function LoginPage() {
useEffect(() => {
document.querySelector('html').classList.add('login-page');
}, []);
return (
// stuff
);
}
A handy package is the React ecosystem for these is React Helmet
import {Helmet} from "react-helmet";
function LoginPage() {
return (
<Helmet>
<html className="loginPage" {...anyOtherStuff} />
<body {...attributesOnBody} />
</Helmet>
);
}
If you would like to add nodes that are adjacent to the root node in the body or React provides you with a solution called Portals that can render anywhere.
For the abiity to change index.html itself, you would not be building yourself a SPA anymore which seems to be case to use React.
you should add a class to your html input to retrieve it.
Here is an exemple :
import React from 'react';
import ReactDOM from 'react-dom';
class X extends React.Component {
render() {
return <h2>TEXT HERE</h2>;
}
}
ReactDOM.render(<X/>, document.getElementById('root'));
React works in a way that attaches itself to some DOM element. In your case, you are attaching it to some element with id of root.
TLDR;
Your index.html will contain the code of your application inside the element with root id during the runtime in the browser. You can see it by inspecting it using browser developer tools.
Your <App /> is the root of your application and if you use dev tools of your browser and you inspect the DOM tree you will see components in there. They are just dynamically attached by React (ReactDOM) and React is in the control of when and how things are rendered.
If your components look something like:
import React from 'react';
function App() {
return <h1 className="title">Hello!</h1>;
}
In Dev tools your DOM structure will looks something like this:
<div id="root">
<h1 class="title">Hello!</h1>
</div>
Here you can see that you have element with root id that you attached your <App /> before and you can see the content of <App />, <h1 class="title" /> together with classes.
That is also how Instagram works and most of the single-page applications or SPAs in short.
There is also a possibility to render static version of your application.
Related
I am having a problem with CSS imports in React, I have a page Home that imports Home.css and a page Hero that imports Hero.css appearently in every page of the application the Hero.css is being applied without even declaring it how can I fix this? These are the following components:
App:
import './App.css';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from './pages/home/Home';
import Hero from './pages/hero/Hero';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />}></Route>
<Route path="/hero" element={<Hero />} ></Route>
</Routes>
</Router>
);
}
export default App;
Hero:
import './Hero.css';
function Hero() {
return <div>
<h1>Hero!</h1>
<button className='glow-on-hover' disabled>test 1</button>
<button className='small-button glow-on-hover'>test 2</button>
<button className='small-button glow-on-hover'>test 3</button>
</div>;
}
export default Hero;
Hero.css:
div {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
justify-items: center;
background-color: #002bff;
}
Home:
import './Home.css';
function Home() {
return <div>
<p>Home!</p>
</div>;
}
export default Home;
The div in the Home component is blue even though the Home.module.css is empty and I declared that the div must be blue only in the Hero.module.css how can I fix this?
First, it's important to understand that importing CSS into a JS page is not actually a feature that JavaScript has. It's an instruction to a bundler like Webpack to include this CSS in the build process.
Moreover, CSS has no native means of scoping it's effects to a cetain component. It's your responsibility to apply the scoping via a class etc.
For example:
React
return <div className="component-hero">
...
CSS
.component-hero {
...
}
Edit:
While the information above is indeed the nature of CSS, there are apparently available tools for automating the scoping with unique identifiers. See references in other answers.
Since there is no built-in scoping mechanism to limit CSS Rules to specific components, This behavior is completely normal, Which results in all your div elements in the component tree to be effected by this import.
I would recommend using CSS Classes to have a layer of scope at least semantically.
<div className="hero-container">
// nested jsx...
</div>
And then add CSS rules in your hero.css file:
.hero-container {
// css-rules
}
create-react-app toolchain has a concept called CSS Modules, If you happen to be using this toolchain, checkout official documentation of CSS Modules here.
Since all our CSS is bundled into a single index.css file at the end of the day, It's harder to maintain distinct class names in larger projects. So, it's better to use a more elegant solution like CSS Modules or third-party libraries that style our components in a tightly coupled fashion, like styled-components etc.
That because you apply the CSS as global.when you are importing in css like import './Home.css';.So it is apply as global. If you need to apply CSS styles as scope to component, you can use different options as below.
One option.
you can use module.css file. According to the official repo.“CSS files in which all class names and animation names are scoped locally by default”.In here you are you can declare styles using classes. but this is not supported to css id.so always to remember declare classes inside the module.css file.
let's deeper in to this.
let say I have declare home.module.css file as this.
.home{
background:green
}
then you cam import this to your jsx file as below and apply this class as below.
import homeStyles from './home.module.css';
export const Home= () => {
return (
<section className={homeStyles.home}>
module.css example
</section>
);
};
when looking at the code you can get idea that I have declared variable by this line," import homeStyles from './home.module.css';".and I am accessing that class inside the section div using homeStyles.home.That because homeStyles is a object that contain the home class property.
Second Option
You can use Styled components. See official doc.This is a third party library. but has much resources to adding and modifying the styles. if you are use, Maetrial ui V5 It also used the this styled component styling pattern.(Just check material ui v5 Styled hook).This styling pattern is not used in the previous material ui versions. The One important this is we can use css classes and css ids for styles the our react elements.
Let say we need to style div with class home which has css propety to background green. we can style this as below.
import styled from "styled-components";
const sectionWrapper = styled.div`
.home {
background: green;
}
#media screen and (max-width: 600px) {
.home {
background: red;
}
}
`;
export const Home = () => {
return (
<sectionWrapper>
<div className="home">module.css example</div>
</sectionWrapper>
);
};
As in the module.css file, we can use media queries in the styled component as well. I have add a media query in the example as well. It explain s that screen size less than 600px,that home class div make background red. You can get better idea about this from their official site. see
I have a React component that contains some third-party <Button/> elements, and I want to rearrange the tab-ordering, but it doesn't look like the component accepts a tabIndex prop. I have something like this:
import {Button} from 'thirdpartylibrary';
import TextPanel from './TextPanel.js';
const Component = ()=>{
...
return (<>
<TextPanel tabIndex={1}/>
<div className="buttons-wrapper">
<Button tabIndex={2}>Btn1</Button>
<Button tabIndex={3}>Btn2</Button>
</div>
</>);
}
Basically, I want <TextPanel/> to get focus first and then the <Button/>, but the focus always starts from the <Button/> first. The browser inspector shows that the rendered HTML buttons don't pick up the tabindexes I assigned their "corresponding" react components. For what it's worth, I checked the <Button/> component's source code and it looks like it eventually inherits from a ElementAttributes<HTMLButtonElement> - does this mean that there's some way of assigning normal html props to it?
Visit Next.js and notice the page request in the network tab. Preview shows not just the HTML but completely pre-styled page.
When we use Styled-Components and Material-UI they have exposed ServerStyleSheet which is used for serving the required styles for the first render within the HTML.
import { ServerStyleSheet } from 'styled-components'
import { ServerStyleSheets } from '#material-ui/core/styles'
How can we achieve same output when using react-bootstrap or custom css like test.css?
Do you care if its a test.css or React bootstrap - Instead why not just inline all critical stylesheets?
It might be worth trying out their experimental feature
Add experimental: { optimizeCss: true } to next.config.js
Install critters#0.0.7 as a dependency
Via How to inline CSS in the head tag of a NextJS project?
Add your style file on the the _app file, you can create this file inside the pages directory in nextjs
import { AppProps } from "next/app";
import 'bootstrap/dist/css/bootstrap.min.css';
import "../your_style.css";
function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default App;
for react-bootstrap , you need to add npm i react-bootstrap bootstrap
Nextjs allows you to display SSG/SSR pages and javascript-disabled
users will still be able to see your app but the layout will be messy
if you use react-bootstrap components to build your layout.
To use react-bootstrap at SSR:
Install :
npm i react-bootstrap bootstrap
Import bootstrap styles in your _app.js:
import 'bootstrap/dist/css/bootstrap.min.css';
You can then use your react-bootstrap components as you would do in reactjs:
import {Container, Row, Col} from 'react-bootstrap';
const Layout = () => (
<>
<Container fluid>
<Row>
<Col>
<p>Running on Next.js at SSR</p>
</Col>
</Row>
</Container>
</>
);
export default Layout;
use Tailwind css
https://tailwindcss.com/
We can simply use classes and it make everything super easy for you design
I am trying to learn redux and react and I sort of getting how it all works but every example I see is so simple that when I started my own webpage I got stuck rightway.
All the examples are just one or 2 components on a blank page, they might be styled to look nice but there is nothing else, no headers, footers, no nav bars nothing.
So for me, I have a header, footer, main container and a side bar, that lists all the users items that are clickable.
I have no clue where to write the static html(are they dump components or just html?), I don't know how to render multiple smart components(side bar, main container what displays contents of what was clicked on in side bar).
Every tutorial I see gets everything written to the one div
<div id="root"></div>
Do I have many of these for each area and then have mutiple of these?
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
<div id="root"></div> in your index.html is the "target" for your React application and only appears once.
Similarly, you only need to render App to the reactDOM once. Your App component can then render multiple components itself, for example
import React, { Component } from 'react';
import Header from './components/header';
import Footer from './components/footer';
import MainContainer from './components/main_container';
class App extends Component {
render() {
return (
<div>
<Header />
<MainContainer />
<Footer />
</div>
);
}
}
This assumes you have created Header, Footer and MainContainer components. Your App component can be thought of (very simplistically) as a larger component that contains multiple components. Therefore, if you render App to ReactDOM you are effectively rendering the other components contained within App.
Please note: this assumes the use of webpack, babel and es6.
Facebook has a great tutorial for building app in react-native, this section explains redux things:
http://makeitopen.com/tutorials/building-the-f8-app/data/
This section is basically how to architect in ReactJS + Redux, so don't be afraid the react-native things, this section is almost the same as in web apps.
you can find code here
I have been using React and look to use Polymer tags inside of React. React does not recognize Polymer tags as React only handles basic DOM tags. Is there a way to add the Polymer tags to React DOM library?
Yes, it is possible.
Create a polymer element.
<link rel="import" href="../../bower_components/polymer/polymer.html">
Polymer({
is: 'calender-element',
ready: function(){
this.textContent = "I am a calender";
}
});
Make the polymer component a html tag by importing it in a html page. E.g. import it in the index.html of your react application.
<link rel="import" href="./src/polymer-components/calender-element.html">
Use that element in the jsx file.
'use strict';
import React from 'react';
class MyComponent extends React.Component{
render(){
return (
<calender-element></calender-element>
);
}
}
export default MyComponent;
Is it possible to use Polymer inside of React?
Short answer: not really.
Long answer: kinda. You have to create components which directly create the nodes and manipulate attributes. There are also other considerations for children of the element, etc.
Is it possible to use React inside of Polymer?
It's pretty much the same answer this way, you'd have to wrap a React component in a polymer element.
Why?
Polymer (based on web components), and React (a ui component library), are both based on 'components'. Because there's no single way to express a component in web, you'll need to bridge between the various libraries. The same holds true for questions about 'react in angular', 'jquery plugin in react', 'knockout in jquery plugin', 'react in backbone', 'angular with polymer elements which use backbone and react with polymer elements which use angular', etc.
In a case like angular with polymer, you might think it's very simple, but polymer doesn't know about evaluating angular expressions, or any kind of declarative callbacks. You need a bridge in nearly every case, and they're never pretty.
this is a fairly old question but how about https://www.npmjs.com/package/react-polymer ? isn't this a support of polymer components for react?
import reactPolymer from 'react-polymer'; //IMPORTANT: Must be imported before React.
import React from 'react';
reactPolymer.registerAttribute('raised');
reactPolymer.registerAttribute('url');
reactPolymer.registerEvent('response', 'onResponse');
<paper-button raised>another button</paper-button>
<iron-ajax url="http://example.com/" onResponse={this.handleResponse} />
Answer according to current stages of react and polymer
Since this question was asked a while ago and a lot has changed since then, I'd like to add that you can now use polymer elements in react directly but for your custom attributes and events it causes problem it can easily be handle by using react-polymer, It has support for almost all elements, with exception of gold-* elements.
Why would you want to use Polymer with react?
It can further simplify your development process or make it a big mess. It depends on how you use it
Speed of development and ease of use offered by polymer components is unrivaled.
React can further break down your components comprising of polymer components, into manageable pieces.
Simply because, react and JSX is love.
Hey why the hell not??
The answer is YES. But it is not straight forward. So, I tried following some documentations which are around in fact even the official one but the best was this: https://medium.com/jens-jansson/start-using-web-components-in-react-6ccca2ca21f9
I followed the steps mentioned and it worked! I am also mentioning the github repo wherein I tried to integrate the vaadin datepicker and also one of the polymer element paper-input. https://github.com/manit815/react-with-webcomponent
Yes, you can use Polymer element inside react.
Create Polymer element
import { LitElement, html } from 'lit-element';
export class CustomButton extends LitElement {
static get properties() {
return {
isDisabled : { type: Boolean },
buttonType: { type: String },
};
}
constructor() {
super();
this.isDisabled = false;
this.button = 'button';
}
render() {
return html`
<button>
<slot></slot>
</button>
`;
}
}
customElements.define('polymer-button', CustomButton);
Import the element into an HTML file using <script type="module">.
Use the import statement (as shown above) to import it from another ES6 module.
<script type="module" src="./polymer-button.js">
Once you've imported it, you can use a custom element just like you'd use a standard element.
import React from 'react';
export const PolymerButton = () => {
return (
<polymer-button />
)
}
I just tried this today and I was able to successfully use the material elements from their element catalog. I haven't gotten around to testing it thoroughly, but as far as using the tags in React goes, it works and all the html and css is there.
To use existing elements, just follow their using elements guide.