How to add a dropdown menu to my React app? - javascript

I'm building a react app using facebook's:
https://github.com/facebookincubator/create-react-app
along w SASS: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-css-preprocessor-sass-less-etc
I'm at a point now where I need to add a dropdown menu to the header. Similar to the header icons on StackOverflow in the top right that open and close on click.
I know this sounds like a dumb question but what is the right way to do this? Do I need to add a UI Framework like a bootstrap for something like this? I have no need for all the bootstrap theming etc...
Thank you - and please be kind to the question given I'm a solo developer and could really use some help building a solid foundation on my app.
Thanks

Yes you can do this easily with just React:
class Hello extends React.Component {
render() {
return <div className="nav">
<Link />
<Link />
<Link />
</div>;
}
}
class Link extends React.Component {
state = {
open: false
}
handleClick = () => {
this.setState({ open: !this.state.open });
}
render () {
const { open } = this.state;
return (
<div className="link">
<span onClick={this.handleClick}>Click Me</span>
<div className={`menu ${open ? 'open' : ''}`}>
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
</div>
</div>
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
.nav {
display: flex;
border-bottom: 1px solid gray;
background: white;
padding: 0 10px;
}
.link {
width: 100px;
border-right: 1px solid gray;
padding: 10px;
text-align: center;
position: relative;
cursor: pointer;
}
.menu {
opacity: 0;
position: absolute;
top: 40px; // same as your nav height
left: 0;
background: #ededed;
border: 1px solid gray;
padding: 10px;
text-align: center;
transition: all 1000ms ease;
}
.menu.open {
opacity: 1;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

you can use react-select like this :
var Select = require('react-select');
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
function logChange(val) {
console.log("Selected: " + JSON.stringify(val));
}
<Select
name="form-field-name"
value="one"
options={options}
onChange={logChange}
/>
https://github.com/JedWatson/react-select
also this library :
https://www.npmjs.com/package/react-dropdown

Seems like your project is still in his infancy. And that you willing to incorporate a library to your project. So I would definitely recommend you to choose a library right now.
With React you could create your own menu without much effort. But you will also need other components for the rest of your app. And the quality of your menu (and other components) will most likely be greater if you choose a library used by many (rather than your own). For "quality" I mean: UX design, HTML standards, API reusability, number of defects, etc.
If you think your app will be small and won't need an entire UI Framework, you might want to search for an isolated component for menu. Here is a list of navigation components (including the number of github stars of each project):
https://devarchy.com/react/topic/navigation
But in most cases I would choose an entire UI Framework instead: https://devarchy.com/react/topic/ui-framework
And here are some demos of the menu/nav/app-bar of some popular UI Frameworks:
https://ant.design/components/menu/
https://react-bootstrap.github.io/components.html#navs-dropdown
http://www.material-ui.com/#/components/app-bar

Custom dropdown
Dropdown.js
import React, { useState } from "react";
import { mdiMenuDown } from "#mdi/js";
import Icon from "#mdi/react";
export default function DropDown({ placeholder, content }) {
const [active, setactive] = useState(0);
const [value, setvalue] = useState(0);
return (
<div className={active ? "dropdown_wrapper active" : "dropdown_wrapper"}>
<span
onClick={() => {
setactive(active ? 0 : 1);
}}
>
{value ? value : placeholder} <Icon path={mdiMenuDown} />
</span>
<div className="drop_down">
<ul>
{content &&
content.map((item, key) => {
return (
<li
onClick={() => {
setvalue(item);
setactive(0);
}}
key={key}
>
{item}
</li>
);
})}
</ul>
</div>
</div>
);}
dropdown.css
.dropdown_wrapper {
position: relative;
margin-left: 100px;
cursor: pointer;
}
.dropdown_wrapper span {
padding: 12px;
border: 1px solid #a8aaac;
border-radius: 6px;
background-color: #ffffff;
display: flex;
color: #3d3e3f;
font-size: 16px;
letter-spacing: 0;
line-height: 26px;
justify-content: space-between;
text-transform: capitalize;
}
.dropdown_wrapper span svg {
width: 20px;
margin-left: 80px;
fill: #fbb800;
transition: 0.5s ease all;
}
.dropdown_wrapper.active span svg {
transform: rotate(180deg);
transition: 0.5s ease all;
}
.dropdown_wrapper .drop_down {
background-color: #fff;
box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2);
position: absolute;
top: 53px;
width: 100%;
z-index: 9;
border-radius: 6px;
border: 1px solid #a8aaac;
height: 0px;
opacity: 0;
overflow: hidden;
transition: 0.5s ease all;
}
.dropdown_wrapper.active .drop_down {
height: fit-content;
opacity: 1;
transition: 0.5s ease all;
}
.dropdown_wrapper .drop_down ul {
list-style: none;
padding-left: 0;
margin: 0;
padding: 10px;
}
.dropdown_wrapper .drop_down ul li {
padding: 10px 0px;
color: #3d3e3f;
font-size: 16px;
letter-spacing: 0;
line-height: 26px;
text-transform: capitalize;
cursor: pointer;
font-weight: 300;
}
.dropdown_wrapper .drop_down ul li:hover {
color: #faab1e;
transition: 0.5s ease all;
}
parent.js
<DropDown placeholder="select a type" content={["breakfast", "lunch", "dinner", "Snacks"]} />

Related

React component overlap each other

component Publisher.js and other child components projectStatus.js are overlapping each other when Render the Child component. I don't know what's going wrong and how to fix this. You can see the image
this is my Publisher.js
//import useState hook to create menu collapse state
import React, { useState } from "react";
import {NavLink, Outlet} from "react-router-dom"
//import react pro sidebar components
import {
ProSidebar,
Menu,
MenuItem,
SidebarHeader,
SidebarFooter,
SidebarContent,
} from "react-pro-sidebar";
//import icons from react icons
import { FaFileContract } from "react-icons/fa";
import { FiLogOut} from "react-icons/fi";
import { HiDocumentReport } from "react-icons/hi";
import { BiCog } from "react-icons/bi";
import { GiHamburgerMenu } from "react-icons/gi";
//import sidebar css from react-pro-sidebar module and our custom css
import "react-pro-sidebar/dist/css/styles.css";
import "./publisherCss.css";
const Publisher = () => {
//create initial menuCollapse state using useState hook
const [menuCollapse, setMenuCollapse] = useState(false)
//create a custom function that will change menucollapse state from false to true and true to false
const menuIconClick = () => {
//condition checking to change state from true to false and vice versa
menuCollapse ? setMenuCollapse(false) : setMenuCollapse(true);
};
return (
<>
<div id="sidebarHeader">
{/* collapsed props to change menu size using menucollapse state */}
<ProSidebar collapsed={menuCollapse}>
<SidebarHeader>
<div className="logotext">
{/* small and big change using menucollapse state */}
<p>{menuCollapse ? "Evc" : "Publisher "}</p>
</div>
<div className="closemenu" onClick={menuIconClick}>
{/* changing menu collapse icon on click */}
{menuCollapse ? (
<GiHamburgerMenu/>
) : (
<GiHamburgerMenu/>
)}
</div>
</SidebarHeader>
<SidebarContent>
<Menu iconShape="square">
<NavLink to="/publisher/projectstatus"> <MenuItem icon={<FaFileContract />}>Project status</MenuItem> </NavLink>
<MenuItem icon={<HiDocumentReport />}>All project</MenuItem>
<MenuItem icon={<BiCog />}>Settings</MenuItem>
</Menu>
</SidebarContent>
<SidebarFooter>
<NavLink to="/login">
<Menu iconShape="square">
<MenuItem icon={<FiLogOut />}>Logout</MenuItem>
</Menu>
</NavLink>
</SidebarFooter>
</ProSidebar>
</div>
<Outlet />
</>
)
}
export default Publisher;
Publisher.css
#sidebarHeader {
position: absolute;
width: 220px;
display: flex;
}
#sidebarHeader .pro-sidebar {
height: 100vh;
/* position: absolute; */
}
#sidebarHeader .closemenu {
color: rgb(0,7,61);
position: absolute;
right: 0;
z-index: 9999;
line-height: 20px;
border-radius: 50%;
font-weight: bold;
font-size: 22px;
top: 55px;
cursor: pointer;
}
#sidebarHeader .pro-sidebar {
width: 100%;
min-width: 100%;
}
#sidebarHeader .pro-sidebar.collapsed {
width: 80px;
min-width: 80px;
}
#sidebarHeader .pro-sidebar-inner {
background-color: white;
box-shadow: 0.5px 0.866px 2px 0px rgba(0, 0, 0, 0.15);
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout {
overflow-y: hidden;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout .logotext p {
font-size: 20px;
padding: 10px 20px;
color: #000;
font-weight: bold;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout ul {
padding: 0 5px;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout ul .pro-inner-item {
color: #000;
margin: 10px 0px;
font-weight: bold;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout ul .pro-inner-item .pro-icon-wrapper {
background-color: #fbf4cd;
color: #000;
border-radius: 3px;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout ul .pro-inner-item .pro-icon-wrapper .pro-item-content {
color: #000;
}
#sidebarHeader .pro-sidebar-inner .pro-sidebar-layout .active {
background-image: linear-gradient(0deg, #fece00 0%, #ffe172 100%);
}
#sidebarHeader .logo {
padding: 20px;
}
#media only screen and (max-width: 720px) {
html {
overflow: hidden;
}
}
.nav-link .active{
background-color: #ffe172;
}
I think I am doing some wrong CSS override property but I am unable to understand what's wrong I am doing. if anyone know please correct me
if anyone knows how to fix this please tell me. it's appreciated
update:
After updating the CSS display: flex it show the child content in flex but the problem is, I specified width: 220px for the sidebar but the child content not go above the 220px width. you can see the image.
Now how can I fix this to a child can use width?
Your picture is not complete, most likely it's styles or wrong location of "Outlet". I made simplified example, I hope it helps.

custom css are applied randomly

I use scss and styled-components together. Recently I don't know why I started to see a race situation over which styles get applied on the final render. Sometimes, usually, when the app is loaded for the first/second time, styles from scss gets applied and when I do a couple of hard refreshes my custom styles written with styled-components get applied. Do you have any idea why is this happening? I don't want to put it! important everywhere to fix it. I would like to understand it.
The below screenshot shows that _sidebar.scss overrode .sidebar styles I wrote.
after some hard refreshes:
after some refreshes, it is another way around:
Here is a component
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react';
import SidebarLinks from './SidebarLinks';
import FormSelectPrinter from "../printer/FormSelectPrinter"
import sidebarData from "../data/";
import {ModalConsumer} from "../components/ModalContext";
import Modal from "../components/Modal";
import { createGlobalStyle } from "styled-components";
const GlobalSidebarStyle = createGlobalStyle`
.sidebar {
background-color: #303b4a;
padding-left: 0;
padding-right: 0;
padding-bottom:40px;
width: 240px;
}
.user__info {
background: #607D8B;
}
.user__info:hover {
background: #607D8B;
}
.user__name {
color: #fff;
}
.user__email {
color: #303b4a;
}
.dropdown-user-menu {
background: #607D8B;
position: relative;
width: 100%;
float: none;
}
.dropdown-select-language {
background: rgba(96, 125, 139, 0.6);
box-shadow: 0 4px 20px rgba(0,0,0,0.9);
right: -26px;
top: 53px;
user-select: none;
}
.dropdown-user-item:hover, .dropdown-user-item:focus {
color: black !important;
}
.dropdown-user-item {
color: white !important;
}
.navigation {
li {
a {
color: #adb5bd;
padding-left: 15px;
&.active {
color: white !important;
}
}
}
}
.navigation li:not(.navigation__active):not(.navigation__sub--active) a:hover {
background-color: rgba(0, 0, 0, 0.19);
color: white;
}
.id-green {
background-color: #73983F;
}
.language-text-color {
color: white !important;
}
.profile_image_style {
border-radius: 100%;
width: 80px;
height: 80px;
}
`
function Sidebar(props) {
const ModalSelectPrinter = ({onClose, ...otherProps}) => {
return (
<Modal>
<FormSelectPrinter onClose={onClose} md={12}></FormSelectPrinter>
</Modal>
)
};
return (
<>
<GlobalSidebarStyle />
<aside className={`sidebar ${props.sidebarToggled? 'toggled' : ''}`}>
<div className="scrollbar-inner">
<div style={{margin: '50px 0 30px 0'}} onClick={() => props.toggleUserInfo()}>
<div className={`user__info ${props.userInfoShown? 'show' : ''}`}>
<div style={{width: '100%', textAlign: 'center'}}>
<div className="user__name">{user.person === null ? user.name : user.person.full_name}</div>
<div className="user__email">{user.email}</div>
</div>
</div>
<div
className={`dropdown-menu dropdown-user-menu ${props.userInfoShown? 'show' : ''}`}>
<ModalConsumer>
{({showModal}) => (
<a className="dropdown-item dropdown-user-item" onClick = {()=>showModal(ModalSelectPrinter, {})}>Select</a>
)}
</ModalConsumer>
<a className="dropdown-item dropdown-user-item" onClick={() => props.logout()}>Log out</a>
</div>
</div>
<SidebarLinks sidebarData={sidebarData} toggleSidebar={props.toggleSidebar}></SidebarLinks>
</div>
</aside>
</>
)
}
export default Sidebar;

Extra pixels in CSS radiobutton group buttons that won't go away

EDIT: Changed the post name, which was incorrectly titled from another post !!
I have been building a sports app in React over the last several months, and I am struggling with a small cosmetic issue with my radio buttons. Immensely frustrating is the fact that despite my attempt at a reproducible example, the bug does not appear in my example below, although fortunately a variant of the issue is occurring. Here are my buttons:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
oneTwoFour: "1 Graph",
quarter: "All"
}
}
handleQuarterChange = (event) => {
this.setState({ quarter: event.target.value });
};
handleOneTwoFourChange = (event) => {
this.setState({ oneTwoFour: event.target.value });
};
render() {
const { oneTwoFour, quarter } = this.state;
const oneTwoFourOptions = ["1 Graph", "2 Graphs", "4 Graphs"];
const oneTwoFourButtons =
<form>
<div className="blg-buttons">
{oneTwoFourOptions.map((d, i) => {
return (
<label key={'onetwofour-' + i}>
<input
type={"radio"}
value={oneTwoFourOptions[i]}
checked={oneTwoFour === oneTwoFourOptions[i]}
onChange={this.handleOneTwoFourChange}
/>
<span>{oneTwoFourOptions[i]}</span>
</label>
)
})}
</div>
</form>;
const quarterOptions = ["All", "OT", "Half 1", "Half 2", "Q1", "Q2", "Q3", "Q4"];
const quarterButtons =
<form>
<div className="blg-buttons">
{quarterOptions.map((d, i) => {
return (
<label key={'quarter-' + i} style={{"width":"50%"}}>
<input
type={"radio"}
value={quarterOptions[i]}
checked={quarter === quarterOptions[i]}
onChange={this.handleQuarterChange}
/>
<span>{quarterOptions[i]}</span>
</label>
)
})}
</div>
</form>;
return(
<div>
<div style={{"width":"25%", "float":"left", "margin":"0 auto", "padding":"5px"}}>
{quarterButtons}
</div>
<div style={{"width":"25%", "float":"left", "margin":"0 auto", "padding":"5px"}}>
{oneTwoFourButtons}
</div>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
.blg-buttons {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.blg-buttons input[type=radio] {
visibility:hidden;
width:0px;
height:0px;
overflow:hidden;
}
.blg-buttons input[type=radio] + span {
cursor: pointer;
display: inline-block;
vertical-align: top;
line-height: 1;
font-size: 1.0vw;
padding: 0.5vw;
border-radius: 0.35vw;
border: 0.15vw solid #333;
width: 90%;
text-align: center;
color: #333;
background: #EEE;
}
.blg-buttons input[type=radio]:not(:checked) + span {
cursor: pointer;
background-color: #EEE;
color: #333;
}
.blg-buttons input[type=radio]:not(:checked) + span:hover{
cursor: pointer;
background: #888;
}
.blg-buttons input[type=radio]:checked + span{
cursor: pointer;
background-color: #333;
color: #EEE;
}
.blg-buttons label {
line-height: 0;
font-size: calc(0.85vw);
margin-bottom: 0.1vw;
width: 90%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<div id='root'>
Come On Work!
</div>
Also, here is a screenshot of an inspection of the buttons in my app (can be found at bigleaguegraphs.com/nba/shotcharts-pro as well), showing the true error that I am having:
The error is in this overhang of the buttons that is not due to padding or margin. I have seemingly gone through every single aspect of the CSS styling my radio buttons, and I have no idea why the element extends a few extra pixels outward to the right.
Amazingly / unfortunately, this is not occurring in the example above, although there is a different issue in the example above where the label element extends a few extra pixels upward (instead of rightward), that I cannot account for.
Any help with removing this extra couple of pixels on the button group would be very much appreciated!
.blg-buttons {
display: flex;
justify-content: center;
/* flex-wrap: wrap; you shouldn't need this */
flex-direction: column;
flex: 1;
}
.blg-buttons label {
display: flex;
line-height: 0;
font-size: 0.85vw;
flex: 1;
align-items: center;
margin-bottom: 5px; /* you don't need that 0.1vw */
font-weight: 700;
}
.blg-buttons input[type=radio]+span {
cursor: pointer;
display: flex;
flex: 1;
justify-content: center;
vertical-align: top;
line-height: 1;
font-size: 1vw;
padding: .5vw;
border-radius: .35vw;
border: .15vw solid #333;
width: 90%;
/* text-align: center; <-- you don't need this with flex */
color: #333;
background: #eee;
}
You should try and use flexbox where possible. I worked this out by playing with your site, so where i saw .nba_scp_cp_rbs i replaced with .blg-buttons (hope that's right). But yeh, avoid using stuff like width: 90%, with flex you rarely have to explicitly define widths, and you can size things based on padding & margins, leading to way less weird sizing bugs like yours :)
picture proof of it working

Why won't my React accordion animation work?

I've implemented my own responsive accordion in React, and I can't get it to animate the opening of a fold.
This is especially odd because I can get the icon before the title to animate up and down, and, other than the icon being a pseudo-element, I can't seem to see the difference between the two.
JS:
class Accordion extends React.Component {
constructor(props) {
super(props);
this.state = {
active: -1
};
}
/***
* Selects the given fold, and deselects if it has been clicked again by setting "active to -1"
* */
selectFold = foldNum => {
const current = this.state.active === foldNum ? -1 : foldNum;
this.setState(() => ({ active: current }));
};
render() {
return (
<div className="accordion">
{this.props.contents.map((content, i) => {
return (
<Fold
key={`${i}-${content.title}`}
content={content}
handle={() => this.selectFold(i)}
active={i === this.state.active}
/>
);
})}
</div>
);
}
}
class Fold extends React.Component {
render() {
return (
<div className="fold">
<button
className={`fold_trigger ${this.props.active ? "open" : ""}`}
onClick={this.props.handle}
>
{this.props.content.title}
</button>
<div
key="content"
className={`fold_content ${this.props.active ? "open" : ""}`}
>
{this.props.active ? this.props.content.inner : null}
</div>
</div>
);
}
}
CSS:
$line-color: rgba(34, 36, 38, 0.35);
.accordion {
width: 100%;
padding: 1rem 2rem;
display: flex;
flex-direction: column;
border-radius: 10%;
overflow-y: auto;
}
.fold {
.fold_trigger {
&:before {
font-family: FontAwesome;
content: "\f107";
display: block;
float: left;
padding-right: 1rem;
transition: transform 400ms;
transform-origin: 20%;
color: $line-color;
}
text-align: start;
width: 100%;
padding: 1rem;
border: none;
outline: none;
background: none;
cursor: pointer;
border-bottom: 1px solid $line-color;
&.open {
&:before {
transform: rotateZ(-180deg);
}
}
}
.fold_content {
display: none;
max-height: 0;
opacity: 0;
transition: max-height 400ms linear;
&.open {
display: block;
max-height: 400px;
opacity: 1;
}
}
border-bottom: 1px solid $line-color;
}
Here's the CodePen: https://codepen.io/renzyq19/pen/bovZKj
I wouldn't conditionally render the content if you want a smooth transition. It will make animating a slide-up especially tricky.
I would change this:
{this.props.active ? this.props.content.inner : null}
to this:
{this.props.content.inner}
and use this scss:
.fold_content {
max-height: 0;
overflow: hidden;
transition: max-height 400ms ease;
&.open {
max-height: 400px;
}
}
Try the snippet below or see the forked CodePen Demo.
class Accordion extends React.Component {
constructor(props) {
super(props);
this.state = {
active: -1
};
}
/***
* Selects the given fold, and deselects if it has been clicked again by setting "active to -1"
* */
selectFold = foldNum => {
const current = this.state.active === foldNum ? -1 : foldNum;
this.setState(() => ({ active: current }));
};
render() {
return (
<div className="accordion">
{this.props.contents.map((content, i) => {
return (
<Fold
key={`${i}-${content.title}`}
content={content}
handle={() => this.selectFold(i)}
active={i === this.state.active}
/>
);
})}
</div>
);
}
}
class Fold extends React.Component {
render() {
return (
<div className="fold">
<button
className={`fold_trigger ${this.props.active ? "open" : ""}`}
onClick={this.props.handle}
>
{this.props.content.title}
</button>
<div
key="content"
className={`fold_content ${this.props.active ? "open" : ""}`}
>
{this.props.content.inner}
</div>
</div>
);
}
}
const pictures = [
"http://unsplash.it/200",
"http://unsplash.it/200",
"http://unsplash.it/200",
];
var test = (title, text, imageURLs) => {
const images=
<div className='test-images' >
{imageURLs.map((url,i) => <img key={i} src={url} />)}
</div>;
const inner =
<div className='test-content' >
<p>{text} </p>
{images}
</div>;
return {title, inner};
};
const testData = [
test('Title', 'Content',pictures ),
test('Title', 'Content',pictures ),
test('Title', 'Content',pictures ),
test('Title', 'Content',pictures ),
test('Title', 'Content',pictures ),
];
ReactDOM.render(<Accordion contents={testData} />, document.getElementById('root'));
.accordion {
width: 100%;
padding: 1rem 2rem;
display: flex;
flex-direction: column;
border-radius: 10%;
overflow-y: auto;
}
.fold {
border-bottom: 1px solid rgba(34, 36, 38, 0.35);
}
.fold .fold_trigger {
text-align: start;
width: 100%;
padding: 1rem;
border: none;
outline: none;
background: none;
cursor: pointer;
border-bottom: 1px solid rgba(34, 36, 38, 0.35);
}
.fold .fold_trigger:before {
font-family: FontAwesome;
content: "\f107";
display: block;
float: left;
padding-right: 1rem;
transition: transform 400ms;
transform-origin: 20%;
color: rgba(34, 36, 38, 0.35);
}
.fold .fold_trigger.open:before {
transform: rotateZ(-180deg);
}
.fold .fold_content {
max-height: 0;
overflow: hidden;
transition: max-height 400ms ease;
}
.fold .fold_content.open {
max-height: 400px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<div id='root'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Note:
I used ease instead of linear on the transition because I think it's a nicer effect. But that's just personal taste. linear will work as well.
Also, you can continue to conditionally render the content. A slide-down animation is possible, but a slide-up can't be easily achieved. There are some transition libraries that you could explore as well.
However, I think it's easiest to use the state just for conditional classes (as you are doing with the open class). I think conditionally rendering content to the DOM makes your life difficult if you're trying to do CSS animations.

How to use `ReactCSSTransitionGroup` to create a collapse/extend list

I am using ReactJS to create a collapse/extend list with animation. You can check out the code from https://codepen.io/zhaoyi0113/pen/qjRKXE. When the user click on the Extend button at the top, the list should be shown within 1 second and at the mean time the footer should be moved to the bottom. My current code doesn't work very well. First, the list items are not shown with the correct animation style. It seems that all items are rendered at the same time. Second, the footer component move to the bottom immediately after I click extend button. How can I implement the list correctly with reactjs animation?
See the Pen React Animation Demo by joey (#zhaoyi0113) on CodePen.
Below is the reactjs code I am using:
const ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
const Container = React.createClass({
getInitialState() {
return {
items: ['Click', 'To', 'Remove', 'An', 'Item'],
extend: false
};
},
render() {
return (
<div className="container">
<div className="animation-container">
<div onClick={() => this.expendItems()} className="item">
{this.state.extend?'Collapse':'Extend'}
</div>
<ReactCSSTransitionGroup transitionName="example">
{this.renderItems()}
</ReactCSSTransitionGroup>
<div>Footer</div>
</div>
</div>
);
},
renderItems() {
const items = this.state.extend? this.state.items: [];
console.log('render items ', items);
return items.map((item, i) => {
return (
<div key={item} className="item">
{item}
</div>
);
});
},
expendItems() {
this.setState({extend: !this.state.extend});
}
});
ReactDOM.render(<Container/>, document.body);
With the way ReactCSSTransitionGroup all components render at the same time.
Moreover, you had the wrong initial translation values, you want to transition from negative values to 0, so that it seems like the buttons are sliding down from the under the expand button
body {
font-family: 'Open Sans', sans-sarif;
padding: 25px;
background-color: $color6;
text-align: center;
}
.container {
text-align: center;
vertical-align: middle;
overflow: hidden;
}
.animation-container {
display: inline-block;
}
.item {
background-color: $color3;
width: 400px;
text-align: center;
padding: 10px 5px;
margin-top: 10px;
border-radius: 8px;
font-weight: 600;
color: mix(black, $color3, 60%);
position: relative;
&:hover {
cursor: pointer;
}
}
div > .item {
margin-top: 0px;
}
.example-enter {
top: -240px;
}
.example-enter.example-enter-active {
top: 0px;
transition: top 1s ease;
}
.example-leave {
top: 0px;
transition: top 1s ease;
}
.example-leave.example-leave-active {
top: -240px;
}
https://codepen.io/anon/pen/Gvrgqm

Categories