Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All
Web-React
AJAX and APIs – React

AJAX and APIs

How can I make an AJAX call?


You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch.


Where in the component lifecycle should I make an AJAX call?


You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.


Example: Using AJAX results to set local state


The component below demonstrates how to make an AJAX call in componentDidMount to populate local component state.


The example API returns a JSON object like this:


{
"items": [
{ "id": 1, "name": "Apples", "price": "$2" },
{ "id": 2, "name": "Peaches", "price": "$5" }
]
}

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}

componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}

render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}

Here is the equivalent with Hooks:


function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);

// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])

if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
Is this page useful? Edit this page
Babel, JSX, and Build Steps – React

Babel, JSX, and Build Steps

Do I need to use JSX with React?


No! Check out “React Without JSX” to learn more.


Do I need to use ES6 (+) with React?


No! Check out “React Without ES6” to learn more.


How can I write comments in JSX?


<div>
{/* Comment goes here */}
Hello,
{name}!
</div>

<div>
{/* It also works
for multi-line comments. */
}
Hello,
{name}!
</div>
Is this page useful? Edit this page
Read article
Passing Functions to Components – React

Passing Functions to Components

How do I pass an event handler (like onClick) to a component?


Pass event handlers and other functions as props to child components:


<button onClick={this.handleClick}>

If you need to have access to the parent component in the handler, you also need to bind the function to the component instance (see below).


How do I bind a function to a component instance?


There are several ways to make sure functions have access to component attributes like this.props and this.state , depending on which syntax and build steps you are using.


Bind in Constructor (ES2015)


class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}

Class Properties (ES2022)


class Foo extends Component {
handleClick = () => {
console.log('Click happened');
};
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}

Bind in Render


class Foo extends Component {
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
}
}


Note:


Using Function.prototype.bind in render creates a new function each time the component renders, which may have performance implications (see below).



Arrow Function in Render


class Foo extends Component {
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
}


Note:


Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.



Is it OK to use arrow functions in render methods?


Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.


If you do have performance issues, by all means, optimize!


Why is binding necessary at all?


In JavaScript, these two code snippets are not equivalent:


obj.method();

var method = obj.method;
method();

Binding methods helps ensure that the second snippet works the same way as the first one.


With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this.handleClick}> passes this.handleClick so you want to bind it. However, it is unnecessary to bind the render method or the lifecycle methods: we don’t pass them to other components.


This post by Yehuda Katz explains what binding is, and how functions work in JavaScript, in detail.


Why is my function being called every time the component renders?


Make sure you aren’t calling the function when you pass it to the component:


render() {
// Wrong: handleClick is called instead of passed as a reference!
return <button onClick={this.handleClick()}>Click Me</button>
}

Instead, pass the function itself (without parens):


render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>Click Me</button>
}

How do I pass a parameter to an event handler or callback?


You can use an arrow function to wrap around an event handler and pass parameters:


<button onClick={() => this.handleClick(id)} />

This is equivalent to calling .bind :


<button onClick={this.handleClick.bind(this, id)} />

Example: Passing params using arrow functions


const A = 65 // ASCII character code

class Alphabet extends React.Component {
constructor(props) {
super(props);
this.state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
};
}
handleClick(letter) {
this.setState({ justClicked: letter });
}
render() {
return (
<div>
Just clicked:
{this.state.justClicked}
<ul>
{this.state.letters.map(letter =>
<li key={letter} onClick={() => this.handleClick(letter)}>
{letter}
</li>
)}
</ul>
</div>
)
}
}

Example: Passing params using data-attributes


Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks.


const A = 65 // ASCII character code

class Alphabet extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
};
}

handleClick(e) {
this.setState({
justClicked: e.target.dataset.letter
});
}

render() {
return (
<div>
Just clicked:
{this.state.justClicked}
<ul>
{this.state.letters.map(letter =>
<li key={letter} data-letter={letter} onClick={this.handleClick}>
{letter}
</li>
)}
</ul>
</div>
)
}
}

How can I prevent a function from being called too quickly or too many times in a row?


If you have an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be done by using:



  • throttling : sample changes based on a time based frequency (eg _.throttle )

  • debouncing : publish changes after a period of inactivity (eg _.debounce )

  • requestAnimationFrame throttling : sample changes based on requestAnimationFrame (eg raf-schd )


See this visualization for a comparison of throttle and debounce functions.



Note:


_.debounce , _.throttle and raf-schd provide a cancel method to cancel delayed callbacks. You should either call this method from componentWillUnmount or check to ensure that the component is still mounted within the delayed function.



Throttle


Throttling prevents a function from being called more than once in a given window of time. The example below throttles a “click” handler to prevent calling it more than once per second.


import throttle from 'lodash.throttle';

class LoadMoreButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleClickThrottled = throttle(this.handleClick, 1000);
}

componentWillUnmount() {
this.handleClickThrottled.cancel();
}

render() {
return <button onClick={this.handleClickThrottled}>Load More</button>;
}

handleClick() {
this.props.loadMore();
}
}

Debounce


Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events). The example below debounces text input with a 250ms delay.


import debounce from 'lodash.debounce';

class Searchbox extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.emitChangeDebounced = debounce(this.emitChange, 250);
}

componentWillUnmount() {
this.emitChangeDebounced.cancel();
}

render() {
return (
<input
type="text"
onChange={this.handleChange}
placeholder="Search..."
defaultValue={this.props.value}
/>

);
}

handleChange(e) {
this.emitChangeDebounced(e.target.value);
}

emitChange(value) {
this.props.onChange(value);
}
}

requestAnimationFrame throttling


requestAnimationFrame is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. A function that is queued with requestAnimationFrame will fire in the next frame. The browser will work hard to ensure that there are 60 frames per second (60 fps). However, if the browser is unable to it will naturally limit the amount of frames in a second. For example, a device might only be able to handle 30 fps and so you will only get 30 frames in that second. Using requestAnimationFrame for throttling is a useful technique in that it prevents you from doing more than 60 updates in a second. If you are doing 100 updates in a second this creates additional work for the browser that the user will not see anyway.



Note:


Using this technique will only capture the last published value in a frame. You can see an example of how this optimization works on MDN



import rafSchedule from 'raf-schd';

class ScrollListener extends React.Component {
constructor(props) {
super(props);

this.handleScroll = this.handleScroll.bind(this);

// Create a new function to schedule updates.
this.scheduleUpdate = rafSchedule(
point => this.props.onScroll(point)
);
}

handleScroll(e) {
// When we receive a scroll event, schedule an update.
// If we receive many updates within a frame, we'll only publish the latest value.
this.scheduleUpdate({ x: e.clientX, y: e.clientY });
}

componentWillUnmount() {
// Cancel any pending updates since we're unmounting.
this.scheduleUpdate.cancel();
}

render() {
return (
<div
style={{ overflow: 'scroll' }}
onScroll={this.handleScroll}
>

<img src="/my-huge-image.jpg" />
</div>
);
}
}

Testing your rate limiting


When testing your rate limiting code works correctly it is helpful to have the ability to fast forward time. If you are using jest then you can use mock timers to fast forward time. If you are using requestAnimationFrame throttling then you may find raf-stub to be a useful tool to control the ticking of animation frames.

Is this page useful? Edit this page
Read article
Component State – React

Component State

What does setState do?


setState() schedules an update to a component’s state object. When state changes, the component responds by re-rendering.


What is the difference between state and props ?


props (short for “properties”) and state are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: props get passed to the component (similar to function parameters) whereas state is managed within the component (similar to variables declared within a function).


Here are some good resources for further reading on when to use props vs state :



  • Props vs State

  • ReactJS: Props vs. State


Why is setState giving me the wrong value?


In React, both this.props and this.state represent the rendered values, i.e. what’s currently on the screen.


Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState . Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).


Example of code that will not behave as expected:


incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}

handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.

// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

// The fix is described below!
}

See below for how to fix this problem.


How do I update state with values that depend on the current state?


Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below).


What is the difference between passing an object or a function in setState ?


Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting:


incrementCount() {
this.setState((state) => {
// Important: read `state` instead of `this.state` when updating.
return {count: state.count + 1}
});
}

handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();

// If you read `this.state.count` now, it would still be 0.
// But when React re-renders the component, it will be 3.
}

Learn more about setState


When is setState asynchronous?


Currently, setState is asynchronous inside event handlers.


This ensures, for example, that if both Parent and Child call setState during a click event, Child isn’t re-rendered twice. Instead, React “flushes” the state updates at the end of the browser event. This results in significant performance improvements in larger apps.


This is an implementation detail so avoid relying on it directly. In the future versions, React will batch updates by default in more cases.


Why doesn’t React update this.state synchronously?


As explained in the previous section, React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.


However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.


There are two main reasons:



  • This would break the consistency between props and state , causing issues that are very hard to debug.

  • This would make some of the new features we’re working on impossible to implement.


This GitHub comment dives deep into the specific examples.


Should I use a state management library like Redux or MobX?


Maybe.


It’s a good idea to get to know React first, before adding in additional libraries. You can build quite complex applications using only React.

Is this page useful? Edit this page
Read article
Styling and CSS – React

Styling and CSS

How do I add CSS classes to components?


Pass a string as the className prop:


render() {
return <span className="menu navigation-menu">Menu</span>
}

It is common for CSS classes to depend on the component props or state:


render() {
let className = 'menu';
if (this.props.isActive) {
className += ' menu-active';
}
return <span className={className}>Menu</span>
}


Tip


If you often find yourself writing code like this, classnames package can simplify it.



Can I use inline styles?


Yes, see the docs on styling here.


Are inline styles bad?


CSS classes are generally better for performance than inline styles.


What is CSS-in-JS?


“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.


Note that this functionality is not a part of React, but provided by third-party libraries. React does not have an opinion about how styles are defined; if in doubt, a good starting point is to define your styles in a separate *.css file as usual and refer to them using className .


Can I do animations in React?


React can be used to power animations. See React Transition Group, React Motion, React Spring, or Framer Motion, for example.

Is this page useful? Edit this page
Read article
File Structure – React

File Structure


React doesn’t have opinions on how you put files into folders. That said there are a few common approaches popular in the ecosystem you may want to consider.


Grouping by features or routes


One common way to structure projects is to locate CSS, JS, and tests together inside folders grouped by feature or route.


common/
Avatar.js
Avatar.css
APIUtils.js
APIUtils.test.js
feed/
index.js
Feed.js
Feed.css
FeedStory.js
FeedStory.test.js
FeedAPI.js
profile/
index.js
Profile.js
ProfileHeader.js
ProfileHeader.css
ProfileAPI.js

The definition of a “feature” is not universal, and it is up to you to choose the granularity. If you can’t come up with a list of top-level folders, you can ask the users of your product what major parts it consists of, and use their mental model as a blueprint.


Grouping by file type


Another popular way to structure projects is to group similar files together, for example:


api/
APIUtils.js
APIUtils.test.js
ProfileAPI.js
UserAPI.js
components/
Avatar.js
Avatar.css
Feed.js
Feed.css
FeedStory.js
FeedStory.test.js
Profile.js
ProfileHeader.js
ProfileHeader.css

Some people also prefer to go further, and separate components into different folders depending on their role in the application. For example, Atomic Design is a design methodology built on this principle. Remember that it’s often more productive to treat such methodologies as helpful examples rather than strict rules to follow.


Avoid too much nesting


There are many pain points associated with deep directory nesting in JavaScript projects. It becomes harder to write relative imports between them, or to update those imports when the files are moved. Unless you have a very compelling reason to use a deep folder structure, consider limiting yourself to a maximum of three or four nested folders within a single project. Of course, this is only a recommendation, and it may not be relevant to your project.


Don’t overthink it


If you’re just starting a project, don’t spend more than five minutes on choosing a file structure. Pick any of the above approaches (or come up with your own) and start writing code! You’ll likely want to rethink it anyway after you’ve written some real code.


If you feel completely stuck, start by keeping all files in a single folder. Eventually it will grow large enough that you will want to separate some files from the rest. By that time you’ll have enough knowledge to tell which files you edit together most often. In general, it is a good idea to keep files that often change together close to each other. This principle is called “colocation”.


As projects grow larger, they often use a mix of both of the above approaches in practice. So choosing the “right” one in the beginning isn’t very important.

Is this page useful? Edit this page
Read article