项目作者: hoppula

项目描述 :
React Firebase components with render props
高级语言: TypeScript
项目地址: git://github.com/hoppula/react-firebase-web.git
创建时间: 2019-02-14T13:54:20Z
项目社区:https://github.com/hoppula/react-firebase-web

开源协议:

下载


react-firebase-web ☢️🔥🕸

React Firebase components with render props

react-firebase-web provides useful set of React components with easy-to-use APIs to access most of Firebase’s features.

Installation

Using npm

  1. npm install -S react-firebase-web

Using yarn

  1. yarn add react-firebase-web

Usage

  1. <Firebase
  2. apiKey="AKzuSyD_O5g9322ozW28XRJ3MPgI-Q2sEBwqYmx"
  3. projectId="react-forum-example"
  4. >
  5. <Value path="users/admin">{admin => <div>{admin.name}</div>}</Value>
  6. <List path="users/test/posts" query={ref => ref.orderByKey().limitToLast(10)}>
  7. {last10Posts => (
  8. <ul>
  9. {last10Posts.map(({ key, value: post }) => (
  10. <li key={key}>{post.title}</li>
  11. ))}
  12. </ul>
  13. )}
  14. </List>
  15. <User
  16. children={user => {
  17. return user.uid ? <div>{user.displayName}</div> : <div ></div>
  18. }}
  19. />
  20. <Write method="push" to="users">
  21. {pushToUsers => <AddUser addUser={pushToUsers} ></AddUser>}
  22. </Write>
  23. </Firebase>

CodeSandbox examples

These CodeSandbox examples use firebase-mock, so feel free to mess around as any change is only applied locally and reseted after reload.

Components

Firebase

places Firebase instance to React’s context, so all the other components can access it. You should wrap your app inside component.

Usage

  1. <Firebase
  2. apiKey="your-api-key"
  3. projectId="your-project-id"
  4. databaseUrl="your-database-url (optional)"
  5. firebase={yourCustomFirebaseImplementation} // optional, allows using API compatible implementation, e.g. firebase-mock for tests
  6. >
  7. <YourApp ></YourApp>
  8. </Firebase>

Connected

provides the current Firebase connection status as only argument for children render function.

Usage

  1. <Connected children={connected => (connected ? "Online" : "Offline")} />

List

provides given Firebase path as an array for given children render function. All array items have key and value properties. List gets re-rendered whenever there are updates to referred Firebase data.

You can provide once prop if you do not want realtime updates.

There’s also query prop for limiting results, it accepts a function that gets called with Firebase reference, e.g. ref => ref.orderByKey().limitToLast(10)

Usage

  1. <List
  2. path="list"
  3. children={list => (
  4. <ul>
  5. {list.map(({ key, value: item }) => (
  6. <li key={key}>{item.name}</li>
  7. ))}
  8. </ul>
  9. )}
  10. />

Value

provides value of given Firebase path as an object for given children render function. Value gets re-rendered whenever there are updates to referred Firebase data.

You can provide once prop if you do not want realtime updates.

Usage

  1. <Value path="value" children={value => <div>{value && value.name}</div>} />

Populate

takes from prop (object with shape {key1: true, key2: true, ...}) and populates an array of related objects using with prop (function with key, key => `relatedPath/${key}` ) for given children render function.

All array items have key and value properties. Populate gets re-rendered whenever there are updates to referred Firebase data.

Usage

  1. <Populate
  2. from={bookmarkedArticleIds}
  3. with={articledId => `articles/${articledId}`}
  4. children={articles => (
  5. <ul>
  6. {articles.map(({ key, value: article }) => (
  7. <li key={key}>{article.title}</li>
  8. ))}
  9. </ul>
  10. )}
  11. />

User

component renders given children render function with currently logged in user. Render function will receive an empty object when user is not logged in.

Usage

  1. <User
  2. children={user => {
  3. if (user.uid) {
  4. return <div>{user.displayName} Logout</div>
  5. } else {
  6. return <div>Login</div>
  7. }
  8. }}
  9. />

OAuthLogin

renders given children render function with login function, which can be passed to onClick handler for example.

flow prop accepts popup and redirect as authentication flows.

provider props accepts facebook, github, google and twitter as OAuth providers.

Usage

  1. <OAuthLogin
  2. flow="popup"
  3. provider="google"
  4. children={login => <button onClick={login}>Login with Google</button>}
  5. />

Logout

provides logout function for given children render function, it can then be passed to event handlers, e.g. onClick.

Usage

  1. <Logout children={logout => <button onClick={logout}>Logout</button>} />

Write

provides mutator function for given children render function.

method prop accepts push, set, update and transaction.

to prop accepts path to mutate as a string.

Usage

  1. <Write
  2. method="push"
  3. to="posts"
  4. children={pushToPosts => {
  5. return (
  6. <button onClick={() => pushToPosts({ title: "Test" })}>
  7. Push to posts
  8. </button>
  9. )
  10. }}
  11. />

EmailLogin

logs user in using Firebase Auth’s signInWithEmailAndPassword method.

Given children render function receives single parameter, a function that logs user in.

That function accepts email and password as params and returns a Promise.

Usage

  1. <EmailLogin
  2. children={login => (
  3. <button onClick={() => login("test@email.dev", "password")}>Login</button>
  4. )}
  5. />

Registration

registers new user using Firebase Auth’s createUserWithEmailAndPassword method.

Given children render function receives single parameter, a function that creates new user.

That function accepts email and password as params and returns a Promise.

Usage

  1. <Registration
  2. children={register => (
  3. <button onClick={() => register("test@test.dev", "test")}>
  4. Create user
  5. </button>
  6. )}
  7. />

ResetPassword

sends password reset e-mail using Firebase Auth’s sendPasswordResetEmail method.

Given children render function receives single parameter, a function that sends password reset e-mail.

That function accepts email as a param and returns a Promise.

Usage

  1. <ResetPassword
  2. children={sendResetEmail => (
  3. <button onClick={() => sendResetEmail("test@test.dev")}>
  4. Send reset password e-mail
  5. </button>
  6. )}
  7. />

Upload

is a component that uploads files to Firebase storage.

onUpload prop function is called when upload completes. It receives upload snapshot and rootRef, so you can store references to uploaded files to some other location in your Firebase database.

  1. onComplete = (snapshot, rootRef) => {
  2. rootRef
  3. .child(`users/${this.props.user.uid}/uploads`)
  4. .push(snapshot.downloadURL)
  5. }

path prop defines where uploaded files should be stored.

children render function receives an object with:

  • uploadFiles a function that uploads the provided files, can be used directly as react-dropzone‘s onDrop callback prop.

  • uploads array of user’s uploaded files.

The example below uses react-dropzone.

NOTE: Remember to enable Firebase storage in your Firebase control panel before using Upload component.

Usage

  1. <Upload
  2. onUpload={this.onComplete}
  3. path="uploads"
  4. children={({ uploadFiles, uploads }) => {
  5. return (
  6. <Dropzone onDrop={uploadFiles}>
  7. {uploads.map(upload => {
  8. const { snapshot, error, success } = upload
  9. if (error) {
  10. return <div>Error</div>
  11. }
  12. if (success) {
  13. return <div>Success {snapshot.downloadURL}</div>
  14. }
  15. return <div>Uploading...</div>
  16. })}
  17. </Dropzone>
  18. )
  19. }}
  20. />

Download

allows you to get download url for provided Firebase Storage reference. Given children render function receives an object with url property.

If you set metadata prop as true, provided object will also include metadata object, which includes file metadata, such as contentType.

Usage

  1. <Download
  2. path="https://firebasestorage.googleapis.com/v0/b/example-project-sd5c9.appspot.com/o/uploads%2Factivity.svg?alt=media&token=1e39160x-fgd1-4c15-a4bf-701f12d3d754"
  3. metadata
  4. >
  5. {download => (
  6. <div>
  7. <img src={download.url} /> {download.metadata.contentType}
  8. </div>
  9. )}
  10. </Download>

React Hooks

This project will be likely rewritten using hooks soon, but it will still provide current render prop components as an alternative.

Firestore

Firestore support is in progress, no ETA yet.

License

MIT