i want to split page between styling and app
example
in page style.js
import styled from "styled-components";
//i dont know how to export all const
export const Container = styled.div`
display: flex;
flex-direction: row;
`;
export const Sidebar = styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`;
and in page app.js
import * as All from "./style.js"
//i dont know, how to import all const in style.js
function App(){
return(
<Container>
<Sidebar>
</Sidebar>
</Container>
)}
how to export and import all const when const in style.js there are so many?
another option you can export like this :
import styled from "styled-components";
const Container = styled.div`
display: flex;
flex-direction: row;
`;
const Sidebar = styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`;
export {Container,Sidebar}
and you can import like this :
import { Container,Sidebar } from './style';
function App() {
return (
<Container>
<Sidebar>
</Sidebar>
</Container>
);
}
There is a beautiful way to do that. This way also let you know which component is styled-component or single component.
// style.js
export const Styled = {
Container: styled.div`
display: flex;
flex-direction: row;
`,
Sidebar: styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`,
}
import { Styled } from './style';
function App() {
return (
<Styled.Container>
<Styled.Sidebar>
</Styled.Sidebar>
</Styled.Container>
);
}
Dae Hyeon Mun's approach is great, but you can simplify it further and avoid having to refactor your styles.js file by using a wildcard import, which essentially creates a module object so you don't have to!:
// style.js
export const Container = styled.div`
...
`;
export const Sidebar = styled.div`
...
`;
// app.js
import * as Styled from './style';
function App() {
return (
<Styled.Container>
<Styled.Sidebar>
</Styled.Sidebar>
</Styled.Container>
);
}
More details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#creating_a_module_object
You can use "export const" like you already did for exporting. The simplest way to import those const is:
import * as styled from "./style.js"
//this will import all 'export const' containing 'styled' from "./style.js"
function App(){
return(
<Container>
<Sidebar>
</Sidebar>
</Container>
)}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Related
I am trying to make hamburger menu. I need the styled components to take the info from the state to toggle the menu and it's not happening.
I want that when I click on the open image the sidebar appears and when I click on the close image it disappear.
My Navigation components
import Nav from '../Nav'
import Sidebar from '../Sidebar'
import React, { useState } from 'react'
export const Navigation = () => {
const [isOpen, setIsOpen] = useState(false);
function toggle(){
setIsOpen(!isOpen)
console.log(isOpen)
}
return (
<>
<Sidebar isOpen={isOpen} toggle={toggle}/>
<Nav isOpen={isOpen} toggle={toggle} />
</>
)
}
export default Navigation
The sidebar
import React from 'react'
import { SideContainer, SideList, SideItem,SideTop,SideLogo,SideClose,SideWrapper } from './SidebarElements'
import Logo from '../../assets/shared/desktop/logo.svg'
import close from '../../assets/shared/mobile/icon-close.svg'
const Sidebar = ({isOpen, toggle}) => {
return (
<SideWrapper>
<SideContainer>
<SideTop>
<SideLogo src={Logo} alt="logo" />
<SideClose src={close} isOpen={isOpen} onClick={toggle} alt="close-logo"/>
</SideTop>
<SideList>
<SideItem>HOME </SideItem>
<SideItem>ABOUT US </SideItem>
<SideItem>CREATE YOUR PLAN </SideItem>
</SideList>
</SideContainer>
</SideWrapper>
)
}
export default Sidebar
import styled from 'styled-components';
export const SideWrapper = styled.div`
#media screen and (min-width: 768px) {
display: none;
}
background: white;
position: absolute;
z-index: 999;
top: 0;
justify-content: center;
align-items: center;
text-align: center;
width: 100%;
height: 100%;
transition: 0.3s ease-in-out;
display: flex;
margin-right: ${({ isOpen }) => (isOpen ? "0rem" : "300rem")};
}
The nav
import React from 'react'
import logo from '../../assets/shared/desktop/logo.svg'
import opened from '../../assets/shared/mobile/icon-hamburger.svg'
import { NavLink } from "react-router-dom"
import './nav.css'
import { Nav,NavContainer,NavMenu ,NavLogo,NavOpen } from './NavElements'
const Navbar = ({toggle}) => {
console.log(toggle)
return (
<>
<Nav>
<NavContainer>
<NavLogo src={logo} alt="logo-coffertoast"/>
<NavOpen src={opened} onClick={toggle} alt="logo-open"/>
<NavMenu>
<NavLink className="Items" to="/">HOME</NavLink>
<NavLink className="Items" to="/about">ABOUT US</NavLink>
<NavLink className="Items" to="/plan" >CREATE YOUR PLAN</NavLink>
</NavMenu>
</NavContainer>
</Nav>
</>
)
}
export default Navbar
You are not passing isOpen to SideWrapper -
<SideWrapper>
it should be
<SideWrapper isOpen={isOpen}>
I am trying to build a random color generater with the randomcolor npm package. When a button is clicked a div should change its color randomly. But react doesn't let me use the randomColor function inside of my reatc component and I don't know why.
import './App.css';
import randomColor from 'randomcolor';
import { useState } from 'react';
import styled from 'styled-components';
function App() {
const [randomColor, setRandomColor] = useState('white');
const Generated = styled.div`
background-color: ${randomColor};
transition: all 0.3s;
padding: 4rem 8rem;
border-radius: 10px;
`;
return (
<Container className="App">
<Button
onClick={() => setRandomColor(randomColor({luminosity: "random", hue:"random"}))}
className="generate"
>
Generate
</Button>
<Generated>Generated Color: {randomColor}</Generated>
</Container>
);
}
export default App;
Does anyone know why it says "randomColor" is declared but never used and why I can't use it in my component?
you have silly mistake, change your randomColor and SetRandomColor name javascript confused by the same name with randomColor() function is this correct of your code :
import './App.css';
import randomColor from 'randomcolor';
import { useState } from 'react';
import styled from 'styled-components';
function App() {
const [randomColor2, setRandomColor2] = useState('white');
const Generated = styled.div`
background-color: ${randomColor};
transition: all 0.3s;
padding: 4rem 8rem;
border-radius: 10px;
`;
return (
<Container className="App">
<Button
onClick={() => setRandomColor2(randomColor({luminosity: "random", hue:"random"}))}
className="generate"
>
Generate
</Button>
<Generated>Generated Color: {randomColor2}</Generated>
</Container>
);
}
export default App;
I'm kinda new to react and currently learning. I kinda stucked at this stage - As i started writing a ChatInput component for an another component which was already imported to App.js and to Chat.js as well. But as i saved and refreshed the code. The react router is rendering a blank page. While there's no error in the code.This problem didnt showed up and the page was rendering fine inspite of the chat component was there but without ChatInput.js.
But now even if i include the component into App.js. the react router renders a blank page and if i removes component from app.js. The code renders the elements.
Please help as i'm new and cant able to figure out What's the issue.
I'm currently on React-router V6
App.js
import React from 'react'
import './App.css'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Header from './components/Header'
import styled from 'styled-components'
import Sidebar from './components/Sidebar'
import Chat from './components/Chat'
function App() {
return (
<div className="app">
<BrowserRouter>
<Header />
<AppBody>
<Sidebar />
<Chat />
<Routes>
<Route path="/" element=""></Route>
</Routes>
</AppBody>
</BrowserRouter>
</div>
)
}
export default App
const AppBody = styled.div`
display: flex;
height: 100vh;
`
Chat.js
import React from 'react'
import StarBorderOutLinedIcon from '#material-ui/icons/StarBorderOutlined'
import InfoOutlinedIcon from '#material-ui/icons/InfoOutlined'
import { useSelector } from 'react-redux'
import { selectRoomId } from '../features/appSlice'
import ChatInput from './ChatInput'
import styled from 'styled-components'
function Chat() {
const roomId = useSelector(selectRoomId)
return (
<ChatContainer>
<>
<Header>
<HeaderLeft>
<h4>
<strong>#Room-name</strong>
</h4>
<StarBorderOutLinedIcon />
</HeaderLeft>
<HeaderRight>
<p>
<InfoOutlinedIcon /> Details
</p>
</HeaderRight>
</Header>
<ChatMessages></ChatMessages>
<ChatInput channelId={roomId} />
</>
</ChatContainer>
)
}
export default Chat
const ChatContainer = styled.div`
flex: 0.7;
flex-grow: 1;
overflow-y: scroll;
margin-top: 60px;
`
const Header = styled.div`
display: flex;
justify-content: space-between;
padding: 20px;
border-bottom: 1px solid lightgray;
`
const HeaderLeft = styled.div`
display: flex;
align-items: center;
> h4 {
display: flex;
text-transform: lowercase;
margin-right: 10px;
}
> h4 > .MuiSvgIcon-root {
margin-left: 10px;
font-size: 18px;
}
`
const HeaderRight = styled.div`
> p {
display: flex;
align-items: center;
font-size: 14px;
}
> p > .MuiSvgIcon-root {
margin-right: 5px !important;
font-size: 16px;
}
`
const ChatMessages = styled.div``
ChatInput.js
import React from 'react'
import styled from 'styled-components'
import { Button } from '#material-ui/core'
function ChatInput(channelName, channelId) {
const sendMessage = (e) => {
e.preventDefault()
}
return (
<ChatInputContainer>
<form>
<input placeholder={'Message #ROOM'} />
<Button hidden type="submit" onClick={sendMessage}>
Send
</Button>
</form>
</ChatInputContainer>
)
}
export default ChatInput
const ChatInputContainer = styled.div`
border-radius: 20px;
> form {
position: relative;
display: flex;
justify-content: center;
}
> form > input {
position: fixed;
bottom: 30px;
width: 60%;
border: 1px solid gray;
border-radius: 3px;
padding: 20px;
outline: none;
}
> form > button {
display: none !important;
}
`
Index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store'
import { Provider } from 'react-redux'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
)
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
Index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store'
import { Provider } from 'react-redux'
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById('root'),
)
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
App.js
import React from 'react'
import './App.css'
import { Routes, Route } from 'react-router-dom'
import Header from './components/Header'
import styled from 'styled-components'
import Sidebar from './components/Sidebar'
import Chat from './components/Chat'
function App() {
return (
<div className="app">
<Routes>
<Route path="/" element={
<>
<Header />
<AppBody>
<Sidebar />
<Chat />
</AppBody>
</>
} />
</Routes>
</div>
)
}
export default App
I am having a unique scenario but I am unable to understand this.
When I hover on one DIV then it selects both the sibling DIVS.
I do not want this behaviour.
I want to select only the DIV which is being hovered.
How can I achieve this in ReactJS ?.
The working code is shown below.
App.js
import React,{useState} from 'react';
import "./App.css";
const App = () => {
const [hover, setHover] = useState(false);
const texts = ["Arjun", "Andy"];
let cclass = hover ? "item itemHover":"item";
return (
<div className="wrapper">
{
texts.map((t, i) => (
<div className={cclass} key={i} onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}>
{t}
</div>
))
}
</div>
)
}
export default App;
App.css
.wrapper{
width: 60%;
margin: 10rem auto;
border: 1px solid;
display: flex;
}
.item{
width: 50%;
border: 1px solid grey;
height: auto;
padding: 2rem 3rem;
}
.itemHover{
background: grey;
}
The hover state in App is common for both divs. To make it work you need to
have hover state for each div separate. For this, create a new component TextDiv
import React, {useState} from "react";
import "./styles.css";
export default function TextDiv({t}) {
const [hover, setHover] = useState(false);
let cclass = hover ? "item itemHover":"item";
return (
<div className={cclass} onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}>
{t}
</div>
)
}
and change App.js file
import React, {useState} from "react";
import TextDiv from './TextDiv'
import "./styles.css";
export default function App() {
const texts = ["Arjun", "Andy"];
return (
<div className="wrapper">
{
texts.map((t, i) => (
<TextDiv t={t} key={i}/>
))
}
</div>
)
}
Can you do it with CSS? It's very simple with CSS. Just add this:
.item:hover{
background: grey;
}
I'm trying to style the child component of a styled-component, but it sends the css to the parent instead of the child/ This is my code,
export const Card = styled.div`
position: relative;
${props => props.horizontal && `
${CardImage}{
max-height: 60%;
overflow: hidden;
}`}
`
export const CardImage = styled.div`
position: relative;
`
EDIT: When I add a condition before rendering that's when it doesn't work
You're almost there, you're just missing a $ in your code and you'll need to move the CardImage above the Card component:
export const CardImage = styled.div`
position: relative;
`
export const Card = styled.div`
position: relative;
${CardImage}{
max-height: 60%;
overflow: hidden;
}
`
Edit (04/04/2018):
If you want to add a condition around a whole block like you have, you need to import the css function from styled components and use that:
import styled, {css} from "styled-components";
export const CardImage = styled.div`
position: relative;
`
export const Card = styled.div`
position: relative;
${props => props.horizontal && css` // - Notice the css` here.
${CardImage}{
max-height: 60%;
overflow: hidden;
}
`}
`
const StyledCard = styled.div`
//parent styles goes here
`;
const StyledImage = styled.img`
//image styles
`;
class CardImage extends Component {
render() {
return <StyledImage/>
}
export default class Card extends Component {
render() {
return <StyledCard>
<CardImage/>
</StyledCard>
}
}
Should it work for you?