How to style a component based on state in Styled Components? - reactjs

I am trying to change the input background based on the useState hook in Styled Components in React.
Here is my code:
const [searchActive, setSearchActive] = useState(true);
<div className="search" searchActive={searchActive}>
<input id="input"/>
</div>
Here is my Styled Component code:
.search {
background: ${(searchActive) => (searchActive ? "red" : "yellow")};
}
any advise would be very appreciated.

Creating a component and passing in props will work:
import React from 'react'
import styled from 'styled-components'
const Search = styled.div`
background: ${props => (props.searchActive ? 'red' : `yellow`)};
`
const Parent = () => {
return (
<Search searchActive={searchActive}>
<input id="input" />
</Search>
)
}
export default Parent
Only different is whatever you have style wise for search can be added to the Search component but you do not show any further code so I do not know how you're bringing it in.
You can also externalize the components with something like:
import styled from 'styled-components'
export const Search = styled.div`
background: ${props => (props.searchActive ? 'red' : `yellow`)};
`
then bring it in:
import {Search} from './search.js'

Add 'props' in styled-component like this;
.search {
background: ${props => props.searchActive? "red" : "yellow"};
}

You can declare and directly use Styled Components in jsx . They are not required to be used as a className. Maybe this approach is useful for you.
import React, { useState } from "react";
import styled from "styled-components";
export default function App() {
const [searchActive, setSearchActive] = useState(true);
const [value, setValue] = useState("");
const Search = styled.input`
background: ${(props) => (props.searchActive ? "red" : "yellow")};
`;
return (
<Search
searchActive={searchActive}
value={value}
onChange={(e) => {
setValue(e.target.value);
setSearchActive(false);
}}
/>
);
}

Related

I want to know how to send props through Link

I made two components and I want to send a props after connecting these components by Link. I'm working on it without using redux, but I found a way to send props and made a code, but the value doesn't come out because I think the method is wrong. I'd appreciate it if you let me know thanks.
SingUp.jsx:
This is the component I'm trying to send a prop. I checked that the value comes out well if I put the value in the input tag. So I think you just need to check the link tag part! I only sent the email value and put email in props to check it
import React, { useState } from 'react'
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import SignUpEmailInput from '../components/SingUp/SignUpEmailInput';
import SignUpLoginButton from '../components/SingUp/SignUpLoginButton';
import SignUpNameInpu from '../components/SingUp/SignUpNameInpu';
import SignUpPassInput from '../components/SingUp/SignUpPassInput';
import SignUpUserInput from '../components/SingUp/SignUpUserInput';
const SignUpWrap = styled.div`
flex-direction: column;
display: flex;
position: relative;
z-index: 0;
margin-bottom: calc(-100vh + 0px);
color: rgb(38,38,38);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 18px;
`
function SignUp() {
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [userName, setUserName] = useState("");
const [passWord, setPassWord] = useState("");
return (
<SignUpWrap>
<div>
<SignUpEmailInput email={email} setEmail={setEmail}/>
</div>
<div>
<SignUpNameInpu name={name} setName={setName}/>
</div>
<div>
<SignUpUserInput userName={userName} setUserName={setUserName} />
</div>
<div>
<SignUpPassInput passWord={passWord} setPassWord={setPassWord}/>
</div>
<div >
{/* I used Link here */}
<Link to={{pathname:'/birthday', state:{email:email}}} style={{textDecoration : 'none' ,color: 'inherit'}}>
<div>
<SignUpLoginButton email={email} name={name} userName={userName} passWord={passWord}/>
</div>
</Link>
</div>
</SignUpWrap>
)
}
export default SignUp;
Birthday.jsx:
This is the component that I want to receive a prop. I checked that the two components are moved through Link. Can I also know how to get a props value here? I want to check if it went well through console.log
import React, { useState } from 'react'
function Birthday({email, name, userName, passWord}) {
console.log(location.state.email)
return (
<>
Hi
</>
)
}
export default Birthday;
you can use state prop as below - using RR V6 version FYI
<Link to="/hello" state={{ data: 'dummy' }}>
and use useLocation hook to collect data in respective component as
const location = useLocation();
console.log(location.state);
A sample e.g. below
https://stackblitz.com/edit/react-ts-mxqsgj?embed=1&file=App.tsx
<Link to="/birthday" state={{email : email }} style={{textDecoration : 'none' ,color: 'inherit'}}>
you can get by using useLocation
import React, { useState } from 'react';
import { useLocation } from 'react-router-dom'
function Birthday() {
const location = useLocation()
const { email } = location.state
console.log(email)
return email
}
export default Birthday;

How to send props value to styled component in emotion react?

I am new to MUI and react, I am trying make input textbox component to reuse them, instead of creating every time.
I am trying to set width value by passing as a props. how can I achieve it.
InputText - functional comp
import React from 'react'
import styled from '#emotion/styled'
import { Box } from '#mui/system'
type propsInputText ={
width:string;
}
const TextBox = styled.input`
width:${props => props.width? props.width : '30px;'}
`
function InputText(props: propsInputText) {
return (
<TextBox />
)
}
export default InputText
MainPage - components
import InputText from '../Tools/TextBox/InputText';
<InputText width='200px' />
Note
It is not just to set width only, I am trying pass anything to styled components ex: color,font-size,height.
I found the solution, I just forget to pass the parameter on the functional component,
type propsInputText ={
width:string;
}
const TextBox = styled.input`
width:${props => props.width? props.width : '30px;'}
`
function InputText(props: propsInputText) {
console.log("InputText Props = "+props.width);
return (
<TextBox width={props.width} /> //here I need to add the props
)
}
export default InputText
Do you want something like this?
const InputBox = (props) => {
const TextBox = styled.input(({ theme }) => ({
width: props.width ? props.width : 200,
color: props.color ? props.color : "blue",
background: props.background? props.background : "yellow",
height: props.height? props.height : 40
}));
return <TextBox />;
};
And then you could implement it like this:
<>
<InputBox width={100} color={"white"} background={"black"} height={"10"} />
<InputBox />
</>

How to use styled from react-emotion with HighchartsReact?

I want to wrap HighchartsReact with HighChartWrapper using styled from react-emotion.
Below is the pseudo-code that I am trying.
import HighchartsReact from 'highcharts-react-official';
import styled from 'react-emotion';
const HighChartWrapper = styled(HighchartsReact)`
/* some styles here */
.highcharts-background {
fill: white !important;
}
`;
<HighChartWrapper highcharts={Highcharts} options={chartData} />
The styles are not working. I am aware that styled can style any component as long as it accepts a className prop.
So does anyone has a working example or a workaround for this?
You can wrap your chart component and pass className prop by containerProps, for example:
const Chart = (props) => {
const [options] = useState({
...
});
return (
<HighchartsReact
highcharts={Highcharts}
options={options}
containerProps={{ className: props.className }}
/>;
);
};
const HighChartWrapper = styled(Chart)`
/* some styles here */
.highcharts-plot-border {
fill: black !important;
}
`;
Live demo: https://codesandbox.io/s/highcharts-react-demo-vosjm?file=/demo.jsx
Docs: https://github.com/highcharts/highcharts-react#options-details

Passing custom props to each styled component through Provider

I would like to pass a custom prop (exactly: theme name as string) to each passed styled component through Provider, so it was available throughout the css definition.
ThemeProvider almost does it, but it expects object, not the string. I do not want to pass whole object with theme settings, just the name of my theme.
I do not want to use special theme prop or similar, because then I would have to it manually every single time I create new styled component. Provider seems like the best option if only it cooperated with string.
Is there any possibility to pass a string through Provider to Consumer builded in styled components?
EDIT:
[PARTIAL SOLUTION]
I found what I was looking for when I realized styled-components exports their inner context. That was it. Having access to pure react context gives you original Provider, without any 'only objects' restriction ('only objects' is a styled-components custom provider restriction).
Now I can push to each styled component exactly what I want and if I want.
import styled, { ThemeContext } from 'styled-components';
const StyledComponent = styled.div`
color: ${props => props.theme == 'dark' ? 'white' : 'black'};
`;
const Component = props => {
const theme = 'dark';
return (
<ThemeContext.Provider value={theme}>
<NextLevelComponent>
<StyledComponent />
</NextLevelComponent>
</ThemeContext.Provider>
);
};
Hope I have this correct, from what I've been able to glean. I haven't tried this out but it seems it might work for you. This is lifted directly from the reactjs.org docs regarding context. It passed the string name of the theme down.
const ThemeContext = React.createContext('green');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="blue">
<SomeComponent />
</ThemeContext.Provider>
);
}
}
function SomeComponent(props) {
return (
<div>
<OtherComponent />
</div>
);
}
class OtherComponent extends React.Component {
static contextType = ThemeContext;
render() {
return <ThirdComponent theme={this.context} />
}
}
I hope this helps you understand the idea behind ThemeContext from styled-components. I've passed string "blue" to ThemeContext just to show, that it should not be object and you can use just string.
import React, { useContext } from "react";
import ReactDOM from "react-dom";
import styled, { ThemeContext } from "styled-components";
// Define styled button
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
color: ${props => props.theme};
border: 2px solid ${props => props.theme};
`;
// Define the name of the theme / color (string)
const themeName = "blue";
const ThemedButton = () => {
// Get the name from context
const themeName = useContext(ThemeContext);
return <Button theme={themeName}>Themed color: {themeName}</Button>;
};
function App() {
return (
<div className="App">
<ThemeContext.Provider value={themeName}>
<ThemedButton />
</ThemeContext.Provider>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Demo: https://codesandbox.io/s/styled-components-example-with-themecontext-cso55

How to pass Styled-Component theme variables to Components?

Within my React+StyledComponent app, I have a theme file like so:
theme.js:
const colors = {
blacks: [
'#14161B',
'#2E2E34',
'#3E3E43',
],
};
const theme = {
colors,
};
export default theme;
Currently, I can easily use these colors to style my components like so:
const MyStyledContainer = styled.div`
background-color: ${(props) => props.theme.colors.blacks[1]};
`;
The problem is, how do I pass blacks[1] to a Component as the prop of the color to use like so:
<Text color="black[1]">Hello</Text>
Where Text.js is:
const StyledSpan = styled.span`
color: ${(props) => props.theme.colors[props.color]};
`;
const Text = ({
color,
}) => {
return (
<StyledSpan
color={color}
>
{text}
</StyledSpan>
);
};
Text.propTypes = {
color: PropTypes.string,
};
export default Text;
Currently the above is silently failing and rending the following in the DOM:
<span class="sc-brqgn" color="blacks[1]">Hello</span>
Any ideas on how I can get this to work? Thank you
EDIT: Updated to use styled-components withTheme HOC
New answer
You could wrap the component rendering <Text> in the higher order component (HOC) withTheme provided by styled-components. This enables you to use the theme given to the <ThemeProvider> directly in the React component.
Example (based on the styled-components docs):
import React from 'react'
import { withTheme } from 'styled-components'
import Text from './Text.js'
class MyComponent extends React.Component {
render() {
<Text color={this.props.theme.colors.blacks[1]} />;
}
}
export default withTheme(MyComponent)
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
Old answer
You could import the theme where you render and pass <Text color={theme.blacks[1]} />.
import theme from './theme.js'
...
<Text color={theme.colors.blacks[1]} />
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
You can use defaultProps
import PropTypes from 'prop-types'
MyStyledContainer.defaultProps = { theme }
App.js
App gets theme and passes color to Text
import React, { Component } from 'react'
import styled from 'styled-components'
const Text = styled.div`
color: ${props => props.color || 'inherit'}
`
class App extends Component {
render() {
const { theme } = this.props
return (
<Text color={theme.colors.black[1]} />
)
}
}
export default App
Root.js
Root component passes theme to entire application.
import React, { Component } from 'react'
import { ThemeProvider } from 'styled-components'
import theme from './theme'
import App from './App'
class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
)
}
}
export default Root
If you're using functional components in React and v4.x and higher styled-components, you need to leverage useContext and styled-components' ThemeContext. Together, these allow you to use your theme settings inside of components that aren't styled-components.
import { useContext } from 'react'
import { ThemeContext } from 'styled-components'
export default function MyComponent() {
// place ThemeContext into a context that is scoped to just this component
const themeProps = useContext(ThemeContext)
return(
<>
{/* Example here is a wrapper component that needs sizing params */}
{/* We access the context and all of our theme props are attached to it */}
<Wrapper maxWidth={ themeProps.maxWidth }>
</Wrapper>
</>
)
}
Further reading in the styled-components docs: https://styled-components.com/docs/advanced#via-usecontext-react-hook

Resources