React Context with TypeScript: Context with class components

React Context with TypeScript:  Context with class components

How to use TypeScript in a class component to consume React context in a strongly-typed manner. In this post, we will learn about using React context with class components.

This is another post in a series of posts on React context with TypeScript. In the previous post, we created a complex context and consumed it in a function component.

In this post, we will learn about using React context with class components.

Trying to use the context hook in a class component

We are going to continue using the context we created in the last post that allows consumers to share and set a theme. Let’s update the Header component to be a class component:

class Header extends React.Component {
  render() {
    const { theme, setTheme } = useTheme()!;

    return (
      <div style={{ backgroundColor: theme }}>
        <select
          value={theme}
          onChange={e => setTheme(e.currentTarget.value)}
        >
          <option value="white">White</option>
          <option value="lightblue">Blue</option>
          <option value="lightgreen">Green</option>
        </select>
        <span>Hello!</span>
      </div>
    );
  }
}

There is a problem with this implementation, though:

react

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

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

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? Also, we will see the react hooks example.

Build a simple React Native Pokemon app with React-Navigation

As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology.

Share Code Between React Native and React JS

React provides support for the server-side and frontend. Today, React development services are in demand as more and more organizations are considering software solutions that are crafted from the framework.

Validating React Forms With React-Hook-Form

In this article we will learn how to Validating React Forms With React-Hook-Form . Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long