3D Rendering in the Browser with react-three-fiber

If you are already building simple web apps with React and are looking to go the 3D route, then react-three-fiber is a go-to solution.

What is react-three-fiber?

As per their official documentation page:

react-three-fiber is a React renderer for three.js on the web and react-native

So what exactly is a renderer? Renderers manage how a React tree turns into the underlying platform calls. That means, we can build 3D artifacts in the form of reusable React components(staying in the React paradigm) and react-three-fiber will do the job of converting those components to the corresponding three.js primitives.

A brief intro to three.js

Now that we know that react-three-fiber is an abstraction on top of three.js, let’s spend some time getting to know what three.js is and what it does on the browser side that makes it a go-to solution when it comes to client-side 3D rendering.

Three.js is a wrapper that sits on top of WebGL (Web Graphics Library) and obfuscates all the bulk of the code that would be quite difficult to write yourself from scratch. To quote directly from the three.js documentation:

WebGL is a very low-level system that only draws points, lines, and triangles. To do anything useful with WebGL generally requires quite a bit of code and that is where three.js comes in. It handles stuff like scenes, lights, shadows, materials, textures, 3D math, etc.

With that understanding in place, let’s now get into understanding the core concepts of react-three-fiber.

#react #javascript #web-development #programming #developer

What is GEEK

Buddha Community

3D Rendering in the Browser with react-three-fiber
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

Create 3D Text Meshes in Three.js with React-Three-Fiber

The first time I encountered Three.js I was blown away. It was hard to believe that the intricate 3D scenes I was looking at were not videos, they were being rendered directly in the browser! I wanted to make something with it, anything, just to understand what this technology was and where it fit in the ecosystem of HTML, CSS, and JS.

While there were a few exploratory attempts to incorporate Three.js into early iterations of my site, what’s left now is the spinning text mesh on my site’s home page. In this post I’ll walk through how we can replicate it using Three.js and React, using the amazing react-three-fiber library.

We’ll be making most of what you can see in the sandbox below, so if you’re following along, you’ll need a blank React project in order to use the code.

#software-development #react #threejs #react-three-fiber #javascript

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

August  Larson

August Larson

1657988940

How to Render 3D in React Made Easy with React-three-fiber

What if I told you… that you too can learn to code in 3D objects in React that can wow customers? Learn the basics of the react-three-fiber renderer, and soon enough, you could be able to turn a static page into an art gallery, an interactive map, or any other metaverse thing.

Reasons for using a React renderer 

3D graphics now create enriched experiences for applications users that allow businesses to reach new waves of customers through memorable visuals. They can represent nearly lifelike products like sneakers or backpacks that can be customized.

Advanced renders can take you on a virtual corporate office tour or even let you complete driving exercises in VR. The gallery I mentioned before gave me an out-of-body experience for 10 minutes.

Experience the dreaminess of a react 3D space. Source: Ripple

From the react-three-fiber projects I’ve seen online, I noticed they aim to make a product/service memorable or understood better. But you can also embrace your frontend skill to simply create an experimental portfolio page as a work of art.

Is it hard to do? Making a scene with Three.js

Normally, you’d be using WebGL — the browser’s API for rendering 3D — which is pretty hard. The list of definitions needed for a regular cube is crazy. See this WebGL example from Mozilla.

Rendering is easier with a high-level library called Three.js, which allows you to create a 3D environment using a simpler API. Input just a few lines of code and you can create a React project with a plain scene hosting the cube.

// Setting up a scene that will be used to place objects
const scene = new THREE.Scene();
// Camera is the camera, eyes of your character
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
// We can set some WebGL parameters like antialiasing (softening sharp edges) 
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
// Boom, let's append our scene to the body
document.body.appendChild( renderer.domElement );
// Add light to the scene with Harry Potter's Lumos spell
const mainLight = new THREE.AmbientLight( '#FFFFFF' ); 
const pointLight = new THREE.PointLight( '#FFFFFF' ); 
scene.add( mainLight );
scene.add( pointLight );

To see anything, you need to declare your cube. Pretty simple.


// This is how we create simple cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: '#BADA55' } );
const cube = new THREE.Mesh( geometry, material );
// And add it to the existing scene
scene.add( cube );

Still nothing? Okay, there is one more step.

// recurring function that will render our scene and camera in WebGL renderer
// and request window to draw next frame of animation
const main = () => {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  requestAnimationFrame(main);
  renderer.render(scene, camera);
}
main();

While that was pretty clear, the rest of the code has this annoying 2000-2010 style.

const btn = document.createElement('button');
btn.innerText = 'Click Me';
btn.onclick = () => console.log('I am imperative');
document.body.appendChild(btn);

Now, import react-three-fiber

Mixing modern React applications with jQuery-like code is not the best idea to improve code quality. But react-three-fiber (R3F) is our savior here. The renderer is declarative like React, letting you create a self-contained component of a 3D scene without mind-clouding complexity.

Add R3F and Three.js as dependencies to your existing Create React App. Alternatively, use the TSH React starter with the usage of yarn add three @react-three/fiber or npm install three @react-three/fiber –save.

Create a functional component that returns the scene setup with light.

import { Canvas, Camera } from 'react-three-fiber'

const MyAwesomeDeclarativeScene = () => {
  return (
    <Canvas camera={{ position: [0, 0, 1], fov: 45 }}>
      {/* We declare three.js object lowerCase without importing */}
      <ambientLight intensity={0.3} color="#FFFFFF" />
      <pointLight intensity={1.0} position={[10, 10, 10]} />
    </Canvas>
  );
}

ReactDOM.render(MyAwesomeDeclarativeScene, document.getElementById('root'));

Your scene is almost ready. Now, add the cube, so that we move forward and explore the exciting options that R3F offers.

<mesh position={[0, 0, -1]}> 
  <boxGeometry args={[1, 1, 1]} /> 
  <meshStandardMaterial color='#BADA55' />
</mesh>

You’re using a mesh React component that is a wrapper for different  Three.js geometries. One of them is boxGeometry which represents the cuboid (or as it says — a box). Add one of the possible Three.js materials simulating depth to see your wonderful baby.

import { Canvas, Camera } from 'react-three-fiber'

const MyAwesomeDeclarativeScene = () => {
  return (
    <Canvas camera={{ position: [0, 0, 5], fov: 45 }}>
      <ambientLight intensity={0.3} color="#FFFFFF" />
      <pointLight intensity={1.0} position={[10, 10, 10]} />
      <mesh position={[0, 0, -1]}> 
        <boxGeometry args={[1, 1, 1]} /> 
        <meshStandardMaterial color='#BADA55' />
      </mesh>
    </Canvas>
  );
}

ReactDOM.render(MyAwesomeDeclarativeScene, document.getElementById('root'));

What does the declarative way of creating 3D in React give you? The direct access to all of React’s bells and whistles! You can build custom, self-contained components, use the reactive state, and do everything that React already has in a simple and efficient way.

How to create a scene with several cuboids

A client walks out of your closet, asking for a simple app with spinning and clickable 3D boxes. The user should be able to control the rotation speed. You need a proof of concept done for lunch (which you pay for). How would you approach the project?

Make usage of the custom Box function component to specify size, color, and speedFactor. The code below assigns a default value to some extra props that can be changed later — no worries.

Use the regular useState statements to track the hovered and active state. Add boxRef to store a reference of your mesh, as it lets you manipulate the object through useFrame callback. Please analyze the code below at your pace until you understand it.

import React, { useMemo, useRef, useState } from 'react';
import { MeshProps, useFrame } from 'react-three-fiber';

type BoxProps = {
  size?: [number, number, number];
  color?: string;
  boxSpeed?: number;
} & MeshProps;

export const Box = ({ size = [1, 1, 1], color = '#FFFFFF', boxSpeed = 0.01, ...meshProps }: BoxProps) => {
  const boxRef = useRef<MeshProps | null>(null);
  const [isHovered, setIsHovered] = useState(false);
  const [isSelected, setIsSelected] = useState(false);

  // It is react-three-fiber way to trigger animation
  // each frame we are changing x, y, z rotation of our box
  useFrame(() => {
    if (!boxRef.current) {
      return;
    }
    boxRef.current.rotation.x += boxSpeed;
    boxRef.current.rotation.y += boxSpeed;
  });
  // it is color memo which indicates state of an item
  const calculatedColor = useMemo(() => {
    if (isSelected && isHovered) {
      return 'orange';
    }
    if (isSelected) {
      return 'yellow';
    }
    if (isHovered && !isSelected) {
      return 'red';
    }
    return color;
  }, [color, isHovered, isSelected]);

  return (
    <mesh
      {...meshProps}
      ref={boxRef}
      onPointerOver={() => setIsHovered(true)}
      onPointerLeave={() => setIsHovered(false)}
      onClick={() => setIsSelected((prev) => !prev)}
      scale={isSelected ? [1.2, 1.2, 1.2] : [1, 1, 1]}
    >
      <boxGeometry args={size} />
      <meshStandardMaterial color={calculatedColor} />
    </mesh>
  );
};

So your scene now uses the awesomely customizable Box component. In order to give the user rotation speed control, add range input to your JSX structure and the useState, which will contain the velocity information.

export const Scene = () => {
  const [speedFactor, setSpeedFactor] = useState(1);

  return (
    <div>
      <label htmlFor="speedFactor">
        Speed factor:
        <input
          name="speedFactor"
          type="range"
          value={speedFactor}
          min={1}
          max={10}
          step={0.1}
          onChange={(e) => setSpeedFactor(+e.currentTarget.value)}
        />
      </label>
      <Canvas camera={{ position: [0, 0, 5], fov: 45 }}>
        <ambientLight intensity={0.3} color="#FFFFFF" />
        <pointLight intensity={1.0} position={[10, 10, 10]} />
        <Box position={[-2, 1, 0]} rotation={[3, 1, 0]} color="hotpink" boxSpeed={0.02 * speedFactor} />
        <Box position={[2, 1, 0]} rotation={[1, 1, 0]} color="cyan" boxSpeed={0.01 * speedFactor} />
        <Box position={[0, -1, 0]} size={[1, 2, 2]} boxSpeed={0.005 * speedFactor} />
      </Canvas>
    </div>
  );
};

A small batch of code can hold a lot of wonder! Once you master react-three-fiber, you’ll be ready to play with Three.js and its rich features. And the result?

React-three-fiber offers awesome developer experience in one pill

The renderer has its own developer experience that goes beyond the declarative style. R3F has outstanding Typescript support that reviews your types at all times.

Performance optimization in R3F is a real game-changer, as the render loop of a three.js scene is completely separated from React’s Virtual DOM.

Besides that, react-three-fiber also has a great ecosystem of utility libraries. There is @react-three/cannon for creating physics-based content or @react-three/drei. The latter offers tons of React three-fiber functions that can save hours on creating a spectacular 3D scene enriched with stunning post-processing effects.

Link: https://tsh.io/blog/react-three-fiber/

#react #3d