Reputation: 1922
I have a functional react component (hooks) called toggle
, that has a button
component, and when clicked, toggles the visibility of an <styledTitle>
(styled-components
). It looks like this:
const Toggle = () => {
const styledTitle = styled.h1`
//some styles
//SUDO CODE: display none if toggle === true else block
`;
const [toggle, setToggle] = useState(false)
const handleToggle = () => {
setToggle(!toggle)
}
<button onClick={handleToggle}>Click me</button>
<styledTitle>Text</styledTitle>
}
I want the styledTitle
to display: none
if the value of toggle
is true
else display: block
How can I do that? Thanks is advance.
Upvotes: 1
Views: 3755
Reputation: 22363
You can pass the state you made to the component
const Toggle = () => {
const styledTitle = styled.h1`
//some styles
display: ${({toggle}) => toggle ? 'none' : 'block'};
`;
const [toggle, setToggle] = useState(false)
const handleToggle = () => {
setToggle(!toggle)
}
<button onClick={handleToggle}>Click me</button>
<styledTitle toggle={toggle}>Text</styledTitle>
}
Like Shubham has in his answer you should rename your variables and make the styled component a separate thing.
// notice the name now in pascal case, components should always be in pascalcase
const StyledTitle = styled.h1`
display: ${({isHidden}) => toggle ? 'none' : 'block'};
`;
const Toggle = () => {
const [toggle, setToggle] = useState(false)
const handleToggle = () => {
setToggle(!toggle)
}
<button onClick={handleToggle}>Click me</button>
// see the prop name here, isHidden, this is better than toggle as a prop
<StyledTitle isHidden={toggle}>Text</StyledTitle>
}
Upvotes: 3
Reputation:
you can use ternary operator on className <styledTitle className={toggle ? "hide" : "show"}>Text</styledTitle>
hide and show are css class with respectively display: none;
and display: block
Upvotes: 0
Reputation: 281696
You can make use props to add conditional styles to your styled-component.
Also define your styled component outside of your fucntional component to ensure that a single instance is created
const StyledTitle = styled.h1`
display: ${props => props.visibility? 'block': 'none'}
`;
const Toggle = () => {
const [toggle, setToggle] = useState(false)
const handleToggle = () => {
setToggle(!toggle)
}
...
<button onClick={handleToggle}>Click me</button>
<StyledTitle visibility={toggle}>Text</StyledTitle>
}
Upvotes: 8