Code Monkey home page Code Monkey logo

reflexbox's Introduction

Reflexbox

Responsive React Flexbox Grid System

http://jxnblk.com/reflexbox

Build Status npm version

Features

  • Simple API for quickly controlling layout
  • Helps promote composability and separation of concerns
  • CSS-in-JS built in - no external dependencies
  • Only generates the CSS needed to render

Getting Started

npm install reflexbox
import React from 'react'
import { Flex, Box } from 'reflexbox'

class Component extends React.Component {
  render() {
    return (
      <Flex p={2} align='center'>
        <Box px={2} w={1/2}>Box A</Box>
        <Box px={2} w={1/2}>Box B</Box>
      </Flex>
    )
  }
}

Usage

// Fractional width
<Box w={1/2} />

// Pixel width
<Box w={128} />

// Responsive widths
<Box w={[ 1, 1/2, 1/4 ]} />

// Padding
<Box p={2} />

// Responsive padding
<Box p={[ 1, 2, 3 ]} />

// Margin
<Box m={2} />

// Responsive margin
<Box m={[ 1, 2, 3 ]} />

// top, right, bottom, left
<Box
  mt={1}
  mr={2}
  mb={3}
  ml={2}
/>

// x-axis
<Box mx={-2} />

// y-axis
<Box my={3} />

// align-items: center
<Flex align='center' />

// justify-content: space-between
<Flex justify='space-between' />

// Flex wrap
<Flex wrap />

// Flex direction column
<Flex column />

// Order
<Box order={2} />

// flex: 1 1 auto
<Box auto />

API

<Flex />

Component primitive with display: flex

<Box />

Primitive for controlling width, margin, padding and more.

Props

Both <Flex /> and <Box /> share the same props.

  • w (number|string) sets width, where numbers 0-1 are percentage values, larger numbers are pixel values, and strings are raw CSS values with units.
  • flex (boolean) sets display: flex
  • wrap (boolean) sets flex-wrap: wrap
  • column (boolean) sets flex-direction: column
  • auto (boolean) sets flex: 1 1 auto
  • order (number) sets order
  • align (string) sets align-items
  • justify (string) sets justify-content

Margin and Padding

Margin and padding props accept numbers 0-4 for values from the spacing scale [ 0, 8, 16, 32, 64 ]. Numbers greater than 4 will be used as pixel values. Negative values can be used for negative margins. Strings can be passed for other CSS values, e.g. mx='auto'

  • m (number|string) margin based on a scale from 0–4.
  • mx (number|string) x-axis margin based on a scale from 0–4.
  • my (number|string) y-axis margin based on a scale from 0–4.
  • mt (number|string) margin-top based on a scale from 0–4.
  • mb (number|string) margin-bottom based on a scale from 0–4.
  • ml (number|string) margin-left based on a scale from 0–4.
  • mr (number|string) margin-right based on a scale from 0–4.
  • p (number|string) padding based on a scale from 0–4.
  • px (number|string) x-axis padding based on a scale from 0–4.
  • py (number|string) y-axis padding based on a scale from 0–4.
  • pt (number|string) padding-top based on a scale from 0–4.
  • pb (number|string) padding-bottom based on a scale from 0–4.
  • pl (number|string) padding-left based on a scale from 0–4.
  • pr (number|string) padding-right based on a scale from 0–4.

Responsive Array Prop Values

All props accept arrays as values for mobile-first responsive styles.

// Set widths for different breakpoints, starting from smallest to largest
// This example will be 100% width below the smallest breakpoint,
// then 50% and 25% for the next two breakpoints respectively
<Box w={[ 1, 1/2, 1/4 ]} />

Null values can be passed to the array to skip a breakpoint.

<Box w={[ 1, null, 1/2 ]} />

Configuration

Values for the breakpoints and space scale can be configured with React Context.

Context can be set manually or with the <ReflexProvider /> component.

import React from 'react'
import { ReflexProvider, Flex, Box } from 'reflexbox'

const space = [ 0, 6, 12, 18, 24 ]
const breakpoints = [ 32, 48, 64 ]

class App extends React.Component {
  render () {
    return (
      <ReflexProvider
        space={space}
        breakpoints={breakpoints}>
        <Flex mx={-2}>
          <Box w={1/4} px={2}>Box</Box>
          <Box w={1/4} px={2}>Box</Box>
          <Box w={1/4} px={2}>Box</Box>
          <Box w={1/4} px={2}>Box</Box>
        </Flex>
      </ReflexProvider>
    )
  }
}

Higher Order Component

The core Reflexbox higher-order component can be used on any element that accepts className as a prop.

import React from 'react'
import { reflex } from 'reflexbox'
import MyInput from './MyInput'

const FlexInput = reflex(MyInput)

const App = () => (
  <div>
    <FlexInput
      w={1/2}
      mb={2}
      defaultValue='Flex Input'
    />
  </div>
)

Caveats

This currently DOES NOT work in Node.js server-side applications. If you need server-side support, see version ^2.2.0 or one of the related libraries below.


Related

MIT License

reflexbox's People

Contributors

hew avatar jxnblk avatar nfcampos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reflexbox's Issues

Does not work with React

Hi,

Followed your examples.

But it does not work.

import React from 'react';
import { Grid, Row, Col } from 'react-flexbox-grid/lib/index';

import React from 'react';
import { Grid, Row, Col } from 'react-flexbox-grid/lib/index';

const Home = () => (
  <div>
    <Grid>
      <Row>
        <Col xs={6} md={3}>Hello, world!</Col>
        <Col xs={6} md={3}>Hello, world!</Col>
        <Col xs={6} md={3}>Hello, world!</Col>
        <Col xs={6} md={3}>Hello, world!</Col>
      </Row>
    </Grid>
  </div>
);

export default Home;

This just prints out empty divs without any class attributes.

Problem with removed border-box and missing docs

I've been using version 2.2.3 for a while now and was about to upgrade to the newest version when I noticed two things.

  1. I can't find any information of what has changed in v.3. It seems like a complete overhaul of the code and many things has changed.

  2. And this is the thing that completely breaks compatibility for me and. Before, this package seemed to have been using Robox. That package set the attribute boxSizing: 'border-box' on Boxes but this is no longer true right now. This means that when I do things such as three elements with w=0.33 and px=2 this will not fit in one row and I get two rows instead. The border-box took care of this but has since been removed. Is there any good remedy for this? Is this is bug? Is this change done of purpose?

"h" prop

Why is there a "w" prop but no "h" prop?

Make a HOC version

Hello,

I really like the API you built for this library. 👍

What would be the scenario when you want to integrate with custom/third-party components ?

For example, imagine I want to create a layout using multiple Paper from material-ui.

To make the Paper a flex element, I'd have to modify its style property (this is what I do at the moment), but I could do better and encapsulate all the "position/layout" logic inside HOC components which would apply the flexbox styles to their children, taking the API you provide :

import { AppBar, Paper } from "material-ui"
import { Box, Flex, Boxed, Flexed } from "reflexbox"

const view = (props) =>

<Flex auto column>
  <AppBar />
  <Flex auto>
    {/* Apply the styles generated from <Boxed auto> to <Paper>Left</Paper> */}
    <Boxed auto>
      <Paper>Left</Paper>
    </Boxed>
    <Boxed auto>
      <Paper>Right</Paper>
    </Boxed>
  </Flex>
</Flex>

I used Boxed and Flexed but the name/API could be anything.

What do you think ? 😄

Add -webkit- prefix

Please consider to add support for Safari 8 adding -webkit- prefix to CSS properties.

Allow changing tag via prop

It'd be rad to use allow custom tags instead of just div—something like <Flex is='a' /> or <Flex tag='a' />.

unpkg

Hey are you planning on making this available via unpkg? It would be great for prototyping on codepen.

Typescript support

Just want to have confirmed that there is indeed no type definition file, correct?

The beginning of a definition file:

declare module 'reflexbox' {

    import * as React from 'react'
    
    export interface BoxProps {
        w?: number | string,
        h?: number | string,
        
        flex?: boolean,
        wrap?: boolean,
        column?: boolean,
        auto?: boolean,
        order?: number,
        align?: "flex-start" | "flex-end" | "center" | "stretch" | "baseline",
        justify?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly",

        m?: number | string,
        mx?: number | string,
        my?: number | string,
        mt?: number | string,
        mb?: number | string,
        ml?: number | string,
        mr?: number | string,

        p?: number | string,
        px?: number | string,
        py?: number | string,
        pt?: number | string,
        pb?: number | string,
        pl?: number | string,
        pr?: number | string,
    }
    
    export class Flex extends React.Component<BoxProps> { } 
    export class Box extends React.Component<BoxProps> { } 
}

Internet Explorer support?

Hello,

I wanted to ask if this library should support IE 10. I found that IE 10 should have -ms prefixed flex properties. If not, is there a turn around to make this work in IE?

Thanks,
Mika

Wrapper Component to reset Grid Size

It would be nice to have a wrapper component to allow changing the default grid size from 12 to whatever is desired. (and be able to nest within other grids of a different size)

<Grid size={10}>
...
</Grid>

Flexbox property clarification

Can I, or would I say how do I, specify the following?:

<Flex min-height="100vh">
<Box flex="0 0 auto">Header</Box>
<Box flex="1 0 auto">Content</Box>
<Box flex="0 0 auto">Title</Box>
<Flex>

ReferenceError: document is not defined

Hi,

When upgrading to 3.0.0-0 I'm having this error:

node_modules/reflexbox/dist/sheet.js:7
var style = document.createElement('style');
                     ^

ReferenceError: document is not defined
    at Object.<anonymous> (/Users/Repos/web/node_modules/reflexbox/dist/sheet.js:7:22)
    at Module._compile (module.js:570:32)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/Repos/web/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Function.cls_wrapMethod [as _load] (/Users/Repos/web/node_modules/newrelic/lib/shimmer.js:256:38)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

Anybody have this too?

[EDIT] - v2.2.2 works fine.

Thanks

import ¯\_(ツ)_/¯: Module not found

I'm getting errors with dist/index.js... it requires ./Flex etc which are not in dist.

ERROR in ./~/reflexbox/dist/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./scale in .../node_modules/reflexbox/dist
 @ ./~/reflexbox/dist/index.js 9:13-31

ERROR in ./~/reflexbox/dist/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./Flex in .../node_modules/reflexbox/dist
 @ ./~/reflexbox/dist/index.js 13:12-29

ERROR in ./~/reflexbox/dist/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./Box in .../node_modules/reflexbox/dist
 @ ./~/reflexbox/dist/index.js 17:11-27

Tried to import { Flex, Box } from 'reflexbox/src' and whitelist node_modules/reflexbox in my webpack babel-loader config, but that choked with:

ERROR in ./~/reflexbox/src/Box.jsx
Module build failed: SyntaxError: .../node_modules/reflexbox/src/Box.jsx: Unexpected token (17:2)
  15 |   pr,
  16 |   fill,
> 17 |   ...props
     |   ^
  18 | }) => {

(same with Flex)

MS prefixing

I see you've added webkit prefixing. However, is there any reason why IE doesn't get prefixed? I see that your understyle library is set up to prefix with -ms-, but it's not functioning.

Warning: Accessing PropTypes deprecated

I'm getting this using React 15.5.4.

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

The issue appears to be in robox here. I'm submitting the issue here, since my app does not depend on robox directly, and it seems to be the same owner.

more properties?

It seems like this only supports a subset of flex-box right now.

Are you open to adding props for the other parts of flexbox? (row, row-reverse, grow, etc.)

If so, I can start sending PRs

Very sluggish in Safari

Not sure what has changed in 2.2.2 from 2.1.0 but my app is extremely sluggish in Safari now. When I drop back down to 2.1.0, the sluggishness disappears. I'm using reflexbox in production so hopefully you have some time to look into this. Great job so far though...reflexbox has been great for my workflow.

Request: ability to set order based on breakpoints

It would be great if it was possible to set order based on the breakpoint. Something like smOrder, mdOrder, etc. Not too sure how to implement this, if you could point me in the right direction I would be happy to send a PR 😄

Could you add some documentation on how to use setBreakpoint?

Am I correct to assume it's possible to set up my own breakpoints object and pass it in some how? I see it in the src folder.

And would using such a function set it globally, or for a specific .

might be cool too. Not sure how hard that would be...

Merge style prop

It looks like 2.2.0 broke passing style down to reflex'd components due to the grid addition:

style={sx} />

I can work around it w/ classes for now, but it'd be nice to have this back. Thanks!

setting things to undefined doesn't work well with cssom

This is with 3.0.0-0.

Something like <Box pr={undefined}>hi</Box> attempts to insert the rule padding-right: which cssom (used in test w/ jsdom) chokes on. Should undefined things just be not turned into rules? For now I'm defaulting things or not setting them instead, but it's a tricky thing and will likely bite others.

auto fill remaining space

Hello
Thanks for great reflexbox!
How can I have two columns as following:
col 1, 320px wide
col 2, fill remaining space

and it should be responsive so this very same columns show on mobile as (convert to rows, but col2 be on top):
col 2, fullwidth
col 1, fullwidth under it

Thank you 💯

New React throwing errors on Base component

Warning: Unknown prop `p` on <div> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop
    in div (created by Base)
    in Base (created by Box)

Sizes sm/md/lg/ not updating when browser window width changes

On a box I have:
<Box sm={12} lg={6} >
I expect the box to be 100% wide when the window is narrow an 50% wide when window is wide/large.
Nothing happens when I resize the window. However, when I reload the page then the box show correct width. Is there something to configure to get this working responsively ?

Failed propType: Invalid prop `is` supplied to `Flex`

Hey again @jxnblk. Take a quick look at this. Maybe I'm doing it wrong.

import { Link } from 'react-scroll'

<Flex is={Link}/>

produces Failed propType: Invalid prop issupplied toFlex``... Though it still works for me.

A quick look at the propTypes suggests to me that by adding React.PropTypes.func to Flex's is prop, might resolve this. I could submit a pull request if you'd like.

Or is it not a bug? Maybe I'm doing it wrong.

Auto-hide in narrow device

Hello,

First of all, thanks @jxnblk for this awesome open source project!

I thought by putting zero in the first element of w parameter will hide the content in small screen.
w={[0, 1/5, 1/5]}

But it turns out the content i.e. 6 7 in below screenshot are still visible. Is this expected behavior? Is there a way to auto-hide in a small screen?

screen shot 2017-12-10 at 8 01 03 pm

Debugging grid not showing up

Why the debugging grid (like here http://jxnblk.com/reflexbox/) is not showing up with the following code?

import { Flex, Box, withReflex } from 'reflexbox'

@withReflex()
export default class Auth extends React.Component {
	static childContextTypes = {
		reflexbox: React.PropTypes.object
	}

	getChildContext() {
		let context = {
    		reflexbox: {
				debug: true,
				breakpoints: {
					sm: '(min-width: 30em)',
					md: '(min-width: 48em)',
					lg: '(min-width: 60em)',
				},
			},
		};
		return context;
	}

	constructor(props) {
		super(props);
	}

	render() {
		return (
			<Paper>
				<form flex>
				 		<Box>
							<h1>Auth</h1>
						</Box>
						<Box>
							<TextField floatingLabelFixed={true} floatingLabelText="Email" />
						</Box>
						<Box>
							<PasswordField floatingLabelFixed={true} floatingLabelText="Password" />
						</Box>
						<Box mt={1}>
							<RaisedButton type="submit" primary={true} label="Sign In" />
						</Box>
						{ this.props.loading && <CircularProgress size={36} thickness={3} /> }
				</form>
			</Paper>
		);
	}
}

withReflex() higher level component not working

Shoudn't the following two be equivalent?

With reflex

@withReflex()
export default class Auth extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		return (
			<Paper flex justify={'space-around'}>
				<form>
					<h1>Auth</h1>
					<TextField floatingLabelFixed={true} floatingLabelText="Email" />
					<PasswordField floatingLabelFixed={true} floatingLabelText="Password" />
					<RaisedButton type="submit" primary={true} label="Sign In" />
					<CircularProgress size={36} thickness={3} />
				</form>
			</Paper>
		);
	}
}

Without reflex

@withReflex()
export default class Auth extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		return (
			<Flex justify={'space-around'}>
				<Paper>
					<form>
						<h1>Auth</h1>
						<TextField floatingLabelFixed={true} floatingLabelText="Email" />
						<PasswordField floatingLabelFixed={true} floatingLabelText="Password" />
						<RaisedButton type="submit" primary={true} label="Sign In" />
						<CircularProgress size={36} thickness={3} />
					</form>
				</Paper>
			</Flex>
		);
	}
}

Full Height

I have 3 columns, content of 3rd column are vertically center aligned, but I need all 3 columns have same height and fill screen vertically:

it is like this :

=
= = =
= = =
= = =

I need to be like this:
= = =
= = =
= = =
= = =
= = =

Update npm package

React 15.x cannot be used together with the current v1.1.0 package (under npm@2) - this was already fixed in a6136c3 - can you push the update to npm under a new (patch) version? :)

Thanks for package by the way!

Introduce shorthand properties

I have a proposal to make the components even more easier to read:

Given the current state

<Flex
  align="center"
  justify="space-between"
  wrap={true}
>

What do you think about:

<Flex center space-between wrap>

Would that make sense?

Should Reflex.match execute on resize?

Correct me if I am wrong but right now Reflex.match is invoked only on componentDidMount and componentWillReceiveProps. Shouldn't it run on "resize" too (mql.addListener) or do you use context for this?

reduce # of wrapper components

Is there any way to do this currently? This makes debugging hard, performance for updating a little worse, and perf debugging using react-addons-perf impossible (due to obscured names).

Every Flex component adds two levels of nesting (minimum):
image

Here's what a perf report looks like using react-addons-perf:
image

Temporary work-around is to revert to 1.x which had simpler components w/ no wrappers

publish latest version on npm plz :)

@jxnblk
this is an awesome project! among all the react flexbox implementations I think this one has the most elegant interface.
npm still has rc1 as latest release. would be good to have all the latest changes.

Ideas for breakpoints to have scales go with them.

Hey, I was thinking that a cool idea for the breakpoints context would be to make the shape one level deeper, and allow you to set a custom set of scales per breakpoint.

const breakpoints = {
  sm: {
    query: '(max-width: 479px)',
    scale: [0, 1, 2, 4, 8, 16]
  },
  md: {
    query: '(min-width: 480px) and (max-width: 839)',
    scale: [0, 2, 4, 6, 8, 32]
  },
  lg: {
    query: '(min-width: 840)',
    scale: [0, 4, 8, 16, 32]
  }
}

This could also be worked into the existing system by checking the object values are object, and if so, go looking for the right children, and if they are strings, just treat them as the queries.

Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.