Adam Daniels

Adam Daniels

1588040400

9 React Conditional Rendering Methods

Controlling the flow of your React application is crucial to getting the result that you are looking for. Learn more about React conditional rendering methods in this video.

Introduction – 00:00
if/else: the entire return value – 01:41
null: prevent rendering by returning null value – 03:43
element variables: storing JSX inside variables – 05:56
ternary operator: inline if/else – 06:57
short-circuit && operator: avoid in React Native – 09:14
IIFEs (immediately invoked function expressions) – 11:11
sub components – 13:24
If components – 14:44
Higher-Order Components (HOCs) – 17:41

GitHub repo: https://github.com/leighhalliday/react-conditionals-demo


JSX is a powerful extension to JavaScript that allows us to define UI components.

If you want to iterate over a list to render more than one component or implement some conditional logic, you have to use pure JavaScript. You don’t have a lot of options with looping, either. Most of the time, map will cover your needs.

But conditional expressions? That’s another story.

You’ve got options

There’s more than one way to use conditional expressions in React. And, as with most things in programming, some are better suited than others depending on the problem you’re trying to solve.

This tutorial covers the most popular conditional rendering methods:

  • If/else
  • Prevent rendering with null
  • Element variables
  • Ternary operator
  • Short-circuit AND operator (&&)
  • Immediately invoked function expressions (IIFEs)
  • Subcomponents
  • Higher-order components (HOCs)

As an example of how all these methods work, a component with a view/edit functionality will be implemented:

You can try and fork all the examples in JSFiddle.

Let’s start with the most naive implementation using an if/else block and build it from there.

If/else

Let’s create a component with the following state:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {text: '', inputText: '', mode:'view'};
  }
}

You’ll use one property for the saved text and another for the text that is being edited. A third property will indicate if you are in edit or view mode.

Next, add some methods for handling input text and the save and edit events:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {text: '', inputText: '', mode:'view'};
    
    this.handleChange = this.handleChange.bind(this);
    this.handleSave = this.handleSave.bind(this);
    this.handleEdit = this.handleEdit.bind(this);
  }
  
  handleChange(e) {
    this.setState({ inputText: e.target.value });
  }
  
  handleSave() {
    this.setState({text: this.state.inputText, mode: 'view'});
  }

  handleEdit() {
    this.setState({mode: 'edit'});
  }
}

Now, for the render method, check the mode state property to either render an edit button or a text input and a save button, in addition to the saved text:

class App extends React.Component {
  // …
  render () {
    if(this.state.mode === 'view') {
      return (
        <div>
          <p>Text: {this.state.text}</p>
          <button onClick={this.handleEdit}>
            Edit
          </button>
        </div>
      );
    } else {
      return (
        <div>
          <p>Text: {this.state.text}</p>
            <input
              onChange={this.handleChange}
              value={this.state.inputText}
            />
          <button onClick={this.handleSave}>
            Save
          </button>
        </div>
      );
    }
}

Here’s the complete Fiddle to try it out:

An if/else block is the easiest way to solve the problem, but I’m sure you know this is not a good implementation.

It works great for simple use cases, and every programmer knows how it works. But there’s a lot of repetition, and the render method looks crowded.

So let’s simplify it by extracting all the conditional logic to two render methods: one to render the input box and another to render the button:

class App extends React.Component {
  // …
  
  renderInputField() {
    if(this.state.mode === 'view') {
      return <div></div>;
    } else {
      return (
          <p>
            <input
              onChange={this.handleChange}
              value={this.state.inputText}
            />
          </p>
      );
    }
  }
  
  renderButton() {
    if(this.state.mode === 'view') {
      return (
          <button onClick={this.handleEdit}>
            Edit
          </button>
      );
    } else {
      return (
          <button onClick={this.handleSave}>
            Save
          </button>
      );
    }
  }

  render () {
    return (
      <div>
        <p>Text: {this.state.text}</p>
        {this.renderInputField()}
        {this.renderButton()}
      </div>
    );
  }
}

Here’s the complete Fiddle to try it out:

Notice that the method renderInputField returns an empty <div> element when the app is in view mode. This is not necessary, however.

Prevent rendering with null

If you want to hide a component, you can make its render method return null, so there’s no need to render an empty (and different) element as a placeholder. One important thing to keep in mind when returning null, however, is that even though the component doesn’t show up, its lifecycle methods are still fired.

Take, for example, the following Fiddle, which implements a counter with two components:

The Number component only renders the counter for even values; otherwise, null is returned. When you look at the console, however, you’ll see that componentDidUpdate is always called regardless of the value returned by render.

Back to our example, change the renderInputField method to look like this:

  renderInputField() {
    if(this.state.mode === 'view') {
      return null;
    } else {
      return (
          <p>
            <input
              onChange={this.handleChange}
              value={this.state.inputText}
            />
          </p>
      );
    }
  }

Here’s the complete Fiddle:

One advantage of returning null instead of an empty element is that you’ll improve the performance of your app a little bit because React won’t have to unmount the component to replace it.

For example, when trying the Fiddle that renders the empty <div> element, if you open the Inspector tab, you’ll see how the <div> element under the root is always updated:

Unlike the case when null is returned to hide the component, where that <div> element is not updated when the Edit button is clicked:

You can learn more here about how React updates the DOM elements and how the diffing algorithm works.

Maybe in this simple example, the performance improvement is insignificant, but when working when big components, there can be a difference. I’ll talk more about the performance implications of conditional rendering later. For now, let’s continue to improve this example.

Element variables

One thing I don’t like is having more than one return statement in methods, so I’m going to use a variable to store the JSX elements and only initialize it when the condition is true:

renderInputField() {
    let input;
    
    if(this.state.mode !== 'view') {
      input = 
        <p>
          <input
            onChange={this.handleChange}
            value={this.state.inputText} />
        </p>;
    }
      
      return input;
  }
  
  renderButton() {
    let button;
    
    if(this.state.mode === 'view') {
      button =
          <button onClick={this.handleEdit}>
            Edit
          </button>;
    } else {
      button =
          <button onClick={this.handleSave}>
            Save
          </button>;
    }
    
    return button;
  }

This gives the same result as returning null from those methods. Here’s the Fiddle to try it out:

The main render method is more readable this way, but maybe it isn’t necessary to use if/else blocks (or something like a switch statement) and secondary render methods. Let’s try a simpler approach.

Ternary operator

Instead of using an if/else block, we can use the ternary conditional operator:

condition ? expr_if_true : expr_if_false

The operator is wrapped in curly braces, and the expressions can contain JSX, optionally wrapped in parentheses to improve readability. It can also be applied in different parts of the component.

Let’s apply it to the example so you can see this in action. I’m going to remove renderInputField and renderButton, and in the render method, I’m going to add a variable to know if the component is in view or edit mode:

render () {
  const view = this.state.mode === 'view';

  return (
      <div>
      </div>
  );
}

Now you can use the ternary operator to return null if the view mode is set, or the input field otherwise:

  // ...

  return (
      <div>
        <p>Text: {this.state.text}</p>
        
        {
          view
          ? null
          : (
            <p>
              <input
                onChange={this.handleChange}
                value={this.state.inputText} />
            </p>
          )
        }

      </div>
  );

Using a ternary operator, you can declare one component to render either a save or edit button by changing its handler and label correspondingly:

  // ...

  return (
      <div>
        <p>Text: {this.state.text}</p>
        
        {
          ...
        }

        <button
          onClick={
            view 
              ? this.handleEdit 
              : this.handleSave
          } >
              {view ? 'Edit' : 'Save'}
        </button>

      </div>
  );

As mentioned before, this operator can be applied in different parts of the component. Here’s the Fiddle to try it out:

Short-circuit AND operator

The ternary operator has a special case where it can be simplified. When you want to render either something or nothing, you can only use the && operator. Unlike the & operator, && doesn’t evaluate the right-hand expression if evaluating only the left-hand expression can decide the final result.

For example, if the first expression evaluates to false (false && …), it’s not necessary to evaluate the next expression because the result will always be false.

In React, you can have expressions like the following:

return (
    <div>
        { showHeader && <Header /> }
    </div>
);

If showHeader evaluates to true, the <Header/> component will be returned by the expression. If showHeader evaluates to false, the <Header/> component will be ignored, and an empty <div> will be returned.

This way, the following expression:

{
  view
  ? null
  : (
    <p>
      <input
        onChange={this.handleChange}
        value={this.state.inputText} />
    </p>
  )
}

Can be turned into:

!view && (
  <p>
    <input
      onChange={this.handleChange}
      value={this.state.inputText} />
  </p>
)

Here’s the complete Fiddle:

Looks better, right?

However, the ternary operator doesn’t always look better. Consider a complex, nested set of conditions:

return (
  <div>
    { condition1
      ? <Component1 />
      : ( condition2
        ? <Component2 />
        : ( condition3
          ? <Component3 />
          : <Component 4 />
        )
      )
    }
  </div>
);

This can become a mess pretty quickly. For that reason, sometimes you might want to use other techniques, like immediately invoked functions.

Immediately invoked function expressions (IIFEs)

As the name implies, IIFEs are functions that are executed immediately after they are defined — there’s no need to call them explicitly.

Generally, this is how you define and execute (at a later point) a function:

function myFunction() {

// ...

}

myFunction();

But if you want to execute the function immediately after it is defined, you have to wrap the whole declaration in parentheses (to convert it to an expression) and execute it by adding two more parentheses (passing any arguments the function may take).

Either this way:

( function myFunction(/* arguments */) {
    // ...
}(/* arguments */) );

Or this way:

( function myFunction(/* arguments */) {
    // ...
} ) (/* arguments */);

Since the function won’t be called in any other place, you can drop the name:

( function (/* arguments */) {
    // ...
} ) (/* arguments */);

Or you can also use arrow functions:

( (/* arguments */) => {
    // ...
} ) (/* arguments */);

In React, you use curly braces to wrap an IIFE, put all the logic you want inside it (if/else, switch, ternary operators, etc.), and return whatever you want to render. For example, here’s how the logic to render the save/edit button could look with an IIFE:

{
  (() => {
    const handler = view 
                ? this.handleEdit 
                : this.handleSave;
    const label = view ? 'Edit' : 'Save';
          
    return (
      <button onClick={handler}>
        {label}
      </button>
    );
  })()
}

Here’s the complete Fiddle:

Subcomponents

Sometimes, an IFFE might seem like a hacky solution. After all, we’re using React — the recommended approaches are to split up the logic of your app into as many components as possible and to use functional programming instead of imperative programming.

So moving the conditional rendering logic to a subcomponent that renders different things based on its props would be a good option. But here, I’m going to do something a bit different to show you how you can go from an imperative solution to more declarative and functional solutions.

I’m going to start by creating a SaveComponent:

const SaveComponent = (props) => {
  return (
    <div>
      <p>
        <input
          onChange={props.handleChange}
          value={props.text}
        />
      </p>
      <button onClick={props.handleSave}>
        Save
      </button>
    </div>
  );
};

As properties, it receives everything it needs to work. In the same way, there’s an EditComponent:

const EditComponent = (props) => {
  return (
    <button onClick={props.handleEdit}>
      Edit
    </button>
  );
};

Now the render method can look like this:

render () {
    const view = this.state.mode === 'view';
    
    return (
      <div>
        <p>Text: {this.state.text}</p>
        
        {
          view
            ? <EditComponent handleEdit={this.handleEdit}  />
            : (
              <SaveComponent 
               handleChange={this.handleChange}
               handleSave={this.handleSave}
               text={this.state.inputText}
             />
            )
        } 
      </div>
    );
}

Here’s the complete Fiddle:

If components

There are libraries like jsx-control-statements that extend JSX to add conditional statements like:

<If condition={ true }>

<span>Hi!</span>

</If>

These libraries provide more advanced components, but if we need something like a simple if/else, we can use a solution similar to Michael J. Ryan’s in the comments for this issue:

const If = (props) => {
  const condition = props.condition || false;
  const positive = props.then || null;
  const negative = props.else || null;
  
  return condition ? positive : negative;
};

// …

render () {
    const view = this.state.mode === 'view';
    const editComponent = <EditComponent handleEdit={this.handleEdit}  />;
    const saveComponent = <SaveComponent 
               handleChange={this.handleChange}
               handleSave={this.handleSave}
               text={this.state.inputText}
             />;
    
    return (
      <div>
        <p>Text: {this.state.text}</p>
        <If
          condition={ view }
          then={ editComponent }
          else={ saveComponent }
        />
      </div>
    );
}

Here’s the complete Fiddle:

Higher-order components (HOCs)

A HOC is a function that takes an existing component and returns a new one with some added functionality:

const EnhancedComponent = higherOrderComponent(component);

Applied to conditional rendering, a HOC could return a different component than the one passed based on some condition:

function higherOrderComponent(Component) {
  return function EnhancedComponent(props) {
    if (condition) {
      return <AnotherComponent { ...props } />;
    }

    return <Component { ...props } />;
  };
}

There’s an excellent article about HOCs by Robin Wieruch that digs deeper into conditional renderings with higher-order components. For this article, I’m going to borrow the concepts of the EitherComponent.

In functional programming, the Either type is commonly used as a wrapper to return two different values. So let’s start by defining a function that takes two arguments, another function that will return a Boolean value (the result of the conditional evaluation), and the component that will be returned if that value is true:

function withEither(conditionalRenderingFn, EitherComponent) {

}

It’s a convention to start the name of the HOC with the word with. This function will return another function that will take the original component to return a new one:

function withEither(conditionalRenderingFn, EitherComponent) {
    return function buildNewComponent(Component) {

    }
}

The component (function) returned by this inner function will be the one you’ll use in your app, so it will take an object with all the properties that it will need to work:

function withEither(conditionalRenderingFn, EitherComponent) {
    return function buildNewComponent(Component) {
        return function FinalComponent(props) {

        }
    }
}

The inner functions have access to the outer functions’ parameters, so now, based on the value returned by the function conditionalRenderingFn, you either return the EitherComponent or the original Component:

function withEither(conditionalRenderingFn, EitherComponent) {
    return function buildNewComponent(Component) {
        return function FinalComponent(props) {
            return conditionalRenderingFn(props)
                ? <EitherComponent { ...props } />
                 : <Component { ...props } />;
        }
    }
}

Or, using arrow functions:

const withEither = (conditionalRenderingFn, EitherComponent) => (Component) => (props) =>
  conditionalRenderingFn(props)
    ? <EitherComponent { ...props } />
    : <Component { ...props } />;

This way, using the previously defined SaveComponent and EditComponent, you can create a withEditConditionalRendering HOC and, with this, create an EditSaveWithConditionalRendering component:

const isViewConditionFn = (props) => props.mode === 'view';

const withEditContionalRendering = withEither(isViewConditionFn, EditComponent);
const EditSaveWithConditionalRendering = withEditContionalRendering(SaveComponent);

You can now use it in the render method, passing all the properties needed:

render () {    
    return (
      <div>
        <p>Text: {this.state.text}</p>
        <EditSaveWithConditionalRendering 
               mode={this.state.mode}
               handleEdit={this.handleEdit}
               handleChange={this.handleChange}
               handleSave={this.handleSave}
               text={this.state.inputText}
             />
      </div>
    );
}

Here’s the complete Fiddle:

Performance considerations

Conditional rendering can be tricky. As I showed you before, the performance of each option can be different. However, most of the time, the differences don’t matter a lot.

But when they do, you’ll need a good understanding of how React works with the virtual DOM and a few tricks to optimizing performance. Here’s a good article about optimizing conditional rendering in React — I totally recommend you read it.

The essential idea is that changing the position of the components due to conditional rendering can cause a reflow that will unmount/mount the components of the app. Based on the example of the article, I created two JSFiddles.

The first one uses an if/else block to show/hide the SubHeader component:

The second one uses the short circuit operator (&&) to do the same:

Open the Inspector and click on the button a few times. You’ll see how the Content component is treated differently by each implementation.

Conclusion

As with many things in programming, there are many ways to implement conditional rendering in React. I’d say that, with exception of the first method (if/else with many returns), you’re free to choose whatever method you want.

You can decide which one is best for your situation based on:

  • Your programming style
  • How complex the conditional logic is
  • How comfortable you are with JavaScript, JSX, and advanced React concepts (like HOCs)

And, all things being equal, always favor simplicity and readability.

#reactjs #javascript #web-development

What is GEEK

Buddha Community

9 React Conditional Rendering Methods
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Beth  Cooper

Beth Cooper

1659694200

Easy Activity Tracking for Models, Similar to Github's Public Activity

PublicActivity

public_activity provides easy activity tracking for your ActiveRecord, Mongoid 3 and MongoMapper models in Rails 3 and 4.

Simply put: it can record what happens in your application and gives you the ability to present those recorded activities to users - in a similar way to how GitHub does it.

!! WARNING: README for unreleased version below. !!

You probably don't want to read the docs for this unreleased version 2.0.

For the stable 1.5.X readme see: https://github.com/chaps-io/public_activity/blob/1-5-stable/README.md

About

Here is a simple example showing what this gem is about:

Example usage

Tutorials

Screencast

Ryan Bates made a great screencast describing how to integrate Public Activity.

Tutorial

A great step-by-step guide on implementing activity feeds using public_activity by Ilya Bodrov.

Online demo

You can see an actual application using this gem here: http://public-activity-example.herokuapp.com/feed

The source code of the demo is hosted here: https://github.com/pokonski/activity_blog

Setup

Gem installation

You can install public_activity as you would any other gem:

gem install public_activity

or in your Gemfile:

gem 'public_activity'

Database setup

By default public_activity uses Active Record. If you want to use Mongoid or MongoMapper as your backend, create an initializer file in your Rails application with the corresponding code inside:

For Mongoid:

# config/initializers/public_activity.rb
PublicActivity.configure do |config|
  config.orm = :mongoid
end

For MongoMapper:

# config/initializers/public_activity.rb
PublicActivity.configure do |config|
  config.orm = :mongo_mapper
end

(ActiveRecord only) Create migration for activities and migrate the database (in your Rails project):

rails g public_activity:migration
rake db:migrate

Model configuration

Include PublicActivity::Model and add tracked to the model you want to keep track of:

For ActiveRecord:

class Article < ActiveRecord::Base
  include PublicActivity::Model
  tracked
end

For Mongoid:

class Article
  include Mongoid::Document
  include PublicActivity::Model
  tracked
end

For MongoMapper:

class Article
  include MongoMapper::Document
  include PublicActivity::Model
  tracked
end

And now, by default create/update/destroy activities are recorded in activities table. This is all you need to start recording activities for basic CRUD actions.

Optional: If you don't need #tracked but still want the comfort of #create_activity, you can include only the lightweight Common module instead of Model.

Custom activities

You can trigger custom activities by setting all your required parameters and triggering create_activity on the tracked model, like this:

@article.create_activity key: 'article.commented_on', owner: current_user

See this entry http://rubydoc.info/gems/public_activity/PublicActivity/Common:create_activity for more details.

Displaying activities

To display them you simply query the PublicActivity::Activity model:

# notifications_controller.rb
def index
  @activities = PublicActivity::Activity.all
end

And in your views:

<%= render_activities(@activities) %>

Note: render_activities is an alias for render_activity and does the same.

Layouts

You can also pass options to both activity#render and #render_activity methods, which are passed deeper to the internally used render_partial method. A useful example would be to render activities wrapped in layout, which shares common elements of an activity, like a timestamp, owner's avatar etc:

<%= render_activities(@activities, layout: :activity) %>

The activity will be wrapped with the app/views/layouts/_activity.html.erb layout, in the above example.

Important: please note that layouts for activities are also partials. Hence the _ prefix.

Locals

Sometimes, it's desirable to pass additional local variables to partials. It can be done this way:

<%= render_activity(@activity, locals: {friends: current_user.friends}) %>

Note: Before 1.4.0, one could pass variables directly to the options hash for #render_activity and access it from activity parameters. This functionality is retained in 1.4.0 and later, but the :locals method is preferred, since it prevents bugs from shadowing variables from activity parameters in the database.

Activity views

public_activity looks for views in app/views/public_activity.

For example, if you have an activity with :key set to "activity.user.changed_avatar", the gem will look for a partial in app/views/public_activity/user/_changed_avatar.html.(|erb|haml|slim|something_else).

Hint: the "activity." prefix in :key is completely optional and kept for backwards compatibility, you can skip it in new projects.

If you would like to fallback to a partial, you can utilize the fallback parameter to specify the path of a partial to use when one is missing:

<%= render_activity(@activity, fallback: 'default') %>

When used in this manner, if a partial with the specified :key cannot be located it will use the partial defined in the fallback instead. In the example above this would resolve to public_activity/_default.html.(|erb|haml|slim|something_else).

If a view file does not exist then ActionView::MisingTemplate will be raised. If you wish to fallback to the old behaviour and use an i18n based translation in this situation you can specify a :fallback parameter of text to fallback to this mechanism like such:

<%= render_activity(@activity, fallback: :text) %>

i18n

Translations are used by the #text method, to which you can pass additional options in form of a hash. #render method uses translations when view templates have not been provided. You can render pure i18n strings by passing {display: :i18n} to #render_activity or #render.

Translations should be put in your locale .yml files. To render pure strings from I18n Example structure:

activity:
  article:
    create: 'Article has been created'
    update: 'Someone has edited the article'
    destroy: 'Some user removed an article!'

This structure is valid for activities with keys "activity.article.create" or "article.create". As mentioned before, "activity." part of the key is optional.

Testing

For RSpec you can first disable public_activity and add require helper methods in the rails_helper.rb with:

#rails_helper.rb
require 'public_activity/testing'

PublicActivity.enabled = false

In your specs you can then blockwise decide whether to turn public_activity on or off.

# file_spec.rb
PublicActivity.with_tracking do
  # your test code goes here
end

PublicActivity.without_tracking do
  # your test code goes here
end

Documentation

For more documentation go here

Common examples

Set the Activity's owner to current_user by default

You can set up a default value for :owner by doing this:

  1. Include PublicActivity::StoreController in your ApplicationController like this:
class ApplicationController < ActionController::Base
  include PublicActivity::StoreController
end
  1. Use Proc in :owner attribute for tracked class method in your desired model. For example:
class Article < ActiveRecord::Base
  tracked owner: Proc.new{ |controller, model| controller.current_user }
end

Note: current_user applies to Devise, if you are using a different authentication gem or your own code, change the current_user to a method you use.

Disable tracking for a class or globally

If you need to disable tracking temporarily, for example in tests or db/seeds.rb then you can use PublicActivity.enabled= attribute like below:

# Disable p_a globally
PublicActivity.enabled = false

# Perform some operations that would normally be tracked by p_a:
Article.create(title: 'New article')

# Switch it back on
PublicActivity.enabled = true

You can also disable public_activity for a specific class:

# Disable p_a for Article class
Article.public_activity_off

# p_a will not do anything here:
@article = Article.create(title: 'New article')

# But will be enabled for other classes:
# (creation of the comment will be recorded if you are tracking the Comment class)
@article.comments.create(body: 'some comment!')

# Enable it again for Article:
Article.public_activity_on

Create custom activities

Besides standard, automatic activities created on CRUD actions on your model (deactivatable), you can post your own activities that can be triggered without modifying the tracked model. There are a few ways to do this, as PublicActivity gives three tiers of options to be set.

Instant options

Because every activity needs a key (otherwise: NoKeyProvided is raised), the shortest and minimal way to post an activity is:

@user.create_activity :mood_changed
# the key of the action will be user.mood_changed
@user.create_activity action: :mood_changed # this is exactly the same as above

Besides assigning your key (which is obvious from the code), it will take global options from User class (given in #tracked method during class definition) and overwrite them with instance options (set on @user by #activity method). You can read more about options and how PublicActivity inherits them for you here.

Note the action parameter builds the key like this: "#{model_name}.#{action}". You can read further on options for #create_activity here.

To provide more options, you can do:

@user.create_activity action: 'poke', parameters: {reason: 'bored'}, recipient: @friend, owner: current_user

In this example, we have provided all the things we could for a standard Activity.

Use custom fields on Activity

Besides the few fields that every Activity has (key, owner, recipient, trackable, parameters), you can also set custom fields. This could be very beneficial, as parameters are a serialized hash, which cannot be queried easily from the database. That being said, use custom fields when you know that you will set them very often and search by them (don't forget database indexes :) ).

Set owner and recipient based on associations

class Comment < ActiveRecord::Base
  include PublicActivity::Model
  tracked owner: :commenter, recipient: :commentee

  belongs_to :commenter, :class_name => "User"
  belongs_to :commentee, :class_name => "User"
end

Resolve parameters from a Symbol or Proc

class Post < ActiveRecord::Base
  include PublicActivity::Model
  tracked only: [:update], parameters: :tracked_values
  
  def tracked_values
   {}.tap do |hash|
     hash[:tags] = tags if tags_changed?
   end
  end
end

Setup

Skip this step if you are using ActiveRecord in Rails 4 or Mongoid

The first step is similar in every ORM available (except mongoid):

PublicActivity::Activity.class_eval do
  attr_accessible :custom_field
end

place this code under config/initializers/public_activity.rb, you have to create it first.

To be able to assign to that field, we need to move it to the mass assignment sanitizer's whitelist.

Migration

If you're using ActiveRecord, you will also need to provide a migration to add the actual field to the Activity. Taken from our tests:

class AddCustomFieldToActivities < ActiveRecord::Migration
  def change
    change_table :activities do |t|
      t.string :custom_field
    end
  end
end

Assigning custom fields

Assigning is done by the same methods that you use for normal parameters: #tracked, #create_activity. You can just pass the name of your custom variable and assign its value. Even better, you can pass it to #tracked to tell us how to harvest your data for custom fields so we can do that for you.

class Article < ActiveRecord::Base
  include PublicActivity::Model
  tracked custom_field: proc {|controller, model| controller.some_helper }
end

Help

If you need help with using public_activity please visit our discussion group and ask a question there:

https://groups.google.com/forum/?fromgroups#!forum/public-activity

Please do not ask general questions in the Github Issues.


Author: public-activity
Source code: https://github.com/public-activity/public_activity
License: MIT license

#ruby  #ruby-on-rails 

Mathew Rini

1615544450

How to Select and Hire the Best React JS and React Native Developers?

Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.

What is React.js?

Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.

React vs React Native

  • React Native is a platform that uses a collection of mobile-specific components provided by the React kit, while React.js is a JavaScript-based library.
  • React.js and React Native have similar syntax and workflows, but their implementation is quite different.
  • React Native is designed to create native mobile apps that are distinct from those created in Objective-C or Java. React, on the other hand, can be used to develop web apps, hybrid and mobile & desktop applications.
  • React Native, in essence, takes the same conceptual UI cornerstones as standard iOS and Android apps and assembles them using React.js syntax to create a rich mobile experience.

What is the Average React Developer Salary?

In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.

* React.js Developer Salary by Country

  • United States- $120,000
  • Canada - $110,000
  • United Kingdom - $71,820
  • The Netherlands $49,095
  • Spain - $35,423.00
  • France - $44,284
  • Ukraine - $28,990
  • India - $9,843
  • Sweden - $55,173
  • Singapore - $43,801

In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.

However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.

It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.

As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.

How to Hire React.js Developers?

  • Conduct thorough candidate research, including portfolios and areas of expertise.
  • Before you sit down with your interviewing panel, do some homework.
  • Examine the final outcome and hire the ideal candidate.

Why is React.js Popular?

React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.

React is scalable. it utilises a single language, For server-client side, and mobile platform.

React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.

React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.

Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.

Final thoughts:

As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.

If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation

#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer

Franz  Becker

Franz Becker

1651604400

React Starter Kit: Build Web Apps with React, Relay and GraphQL.

React Starter Kit — "isomorphic" web app boilerplate   

React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Express, GraphQL and React, containing modern web development tools such as Webpack, Babel and Browsersync. Helping you to stay productive following the best practices. A solid starting point for both professionals and newcomers to the industry.

See getting started guide, demo, docs, roadmap  |  Join #react-starter-kit chat room on Gitter  |  Visit our sponsors:

 

Hiring

Getting Started

Customization

The master branch of React Starter Kit doesn't include a Flux implementation or any other advanced integrations. Nevertheless, we have some integrations available to you in feature branches that you can use either as a reference or merge into your project:

You can see status of most reasonable merge combination as PRs labeled as TRACKING

If you think that any of these features should be on master, or vice versa, some features should removed from the master branch, please let us know. We love your feedback!

Comparison

 

React Starter Kit

React Static Boilerplate

ASP.NET Core Starter Kit

App typeIsomorphic (universal)Single-page applicationSingle-page application
Frontend
LanguageJavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)
LibrariesReact, History, Universal RouterReact, History, ReduxReact, History, Redux
RoutesImperative (functional)DeclarativeDeclarative, cross-stack
Backend
LanguageJavaScript (ES2015+, JSX)n/aC#, F#
LibrariesNode.js, Express, Sequelize,
GraphQL
n/aASP.NET Core, EF Core,
ASP.NET Identity
SSRYesn/an/a
Data APIGraphQLn/aWeb API

Backers

♥ React Starter Kit? Help us keep it alive by donating funds to cover project expenses via OpenCollective or Bountysource!

lehneres Tarkan Anlar Morten Olsen Adam David Ernst Zane Hitchcox  

How to Contribute

Anyone and everyone is welcome to contribute to this project. The best way to start is by checking our open issues, submit a new issue or feature request, participate in discussions, upvote or downvote the issues you like or dislike, send pull requests.

Learn More

Related Projects

  • GraphQL Starter Kit — Boilerplate for building data APIs with Node.js, JavaScript (via Babel) and GraphQL
  • Membership Database — SQL schema boilerplate for user accounts, profiles, roles, and auth claims
  • Babel Starter Kit — Boilerplate for authoring JavaScript/React.js libraries

Support

License

Copyright © 2014-present Kriasoft, LLC. This source code is licensed under the MIT license found in the LICENSE.txt file. The documentation to the project is licensed under the CC BY-SA 4.0 license.


Author: kriasoft
Source Code: https://github.com/kriasoft/react-starter-kit
License: MIT License

#graphql #react 

Juned Ghanchi

1621573085

React Native App Developers India, React Native App Development Company

Expand your user base by using react-native apps developed by our expert team for various platforms like Android, Android TV, iOS, macOS, tvOS, the Web, Windows, and UWP.

We help businesses to scale up the process and achieve greater performance by providing the best react native app development services. Our skilled and experienced team’s apps have delivered all the expected results for our clients across the world.

To achieve growth for your business, hire react native app developers in India. You can count on us for all the technical services and support.

#react native app development company india #react native app developers india #hire react native developers india #react native app development company #react native app developers #hire react native developers