jkisolo.com

Mastering Preact: Checkboxes, Radio Buttons, and Refs Simplified

Written on

Chapter 1: Introduction to Preact

Preact is a lightweight front-end framework that shares similarities with React but offers a simpler and less bulky alternative. In this guide, we will explore how to utilize Preact for front-end development, specifically focusing on checkboxes, radio buttons, and refs.

Section 1.1: Implementing Checkboxes

You can easily integrate checkboxes into your Preact application and capture their selected values. Here's a basic example:

import { Component, render } from "preact";

export default class App extends Component {

toggle = (e) => {

let checked = !this.state.checked;

this.setState({ checked });

};

render(_, { checked }) {

return (

<div>

<input type="checkbox" checked={checked} onClick={this.toggle} />

</div>

);

}

}

if (typeof window !== "undefined") {

render(<App />, document.getElementById("root"));

}

In this code snippet, we initialize the checked state and link it to the checked prop of the checkbox input. The onClick event triggers the toggle method to update the state.

Section 1.2: Utilizing Radio Buttons

Similarly, radio buttons can be implemented to allow users to select one option from a set. Consider the following example:

import { Component, render } from "preact";

export default class App extends Component {

constructor() {

super();

this.state = {

fruit: "apple"

};

}

onChangeValue = (event) => {

this.setState({ fruit: event.target.value });

};

render(_, { fruit }) {

return (

<div>

<input type="radio" value="apple" checked={fruit === "apple"} onChange={this.onChangeValue} /> Apple

<input type="radio" value="orange" checked={fruit === "orange"} onChange={this.onChangeValue} /> Orange

<input type="radio" value="grape" checked={fruit === "grape"} onChange={this.onChangeValue} /> Grape

</div>

);

}

}

if (typeof window !== "undefined") {

render(<App />, document.getElementById("root"));

}

In this example, the onChangeValue method listens for changes in the selection of radio buttons, updating the state accordingly.

Chapter 2: Working with Refs

Section 2.1: Using createRef

To create a reference to a DOM element, you can utilize the createRef function. Here’s how it can be implemented:

import { Component, createRef, render } from "preact";

export default class App extends Component {

ref = createRef();

componentDidMount() {

console.log(this.ref.current);

}

render() {

return <div ref={this.ref}>foo</div>;

}

}

if (typeof window !== "undefined") {

render(<App />, document.getElementById("root"));

}

By assigning our ref to the div, we can access its DOM node when componentDidMount is called.

Section 2.2: Callback Refs

Alternatively, you can use callback refs to obtain a reference to an element. Here’s an example:

import { Component, render } from "preact";

export default class App extends Component {

ref = null;

setRef = (dom) => (this.ref = dom);

componentDidMount() {

console.log(this.ref);

}

render() {

return <div ref={this.setRef}>foo</div>;

}

}

if (typeof window !== "undefined") {

render(<App />, document.getElementById("root"));

}

In this case, the setRef function captures the DOM node and assigns it to this.ref, allowing us to log its value during the component lifecycle.

Conclusion

With Preact, adding checkboxes and radio buttons is straightforward, and accessing DOM elements through refs enhances your application's interactivity.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Success Without Character: A Recipe for Temporary Achievement

Discover how success may open doors, but only character can keep them open in your career journey.

# Five Effective Strategies to Enhance Your Finances, Health, and Time Management

Discover five strategies to improve your finances, health, and time management for a more productive lifestyle.

Optimizing Python Code Performance with %timeit Command

Discover how to efficiently measure and optimize your Python code performance using the %timeit command.

Crafting a Six-Figure Business from Scratch in Just One Year

Discover how I transformed my life from a corporate job to a six-figure business in just two years.

Building a Film Production Company: Insights from Khoa Le

Khoa Le shares essential strategies for launching a successful film production company in today's competitive landscape.

Optimizing Endurance Training: A Review of Modern Techniques

A concise review of a valuable resource for runners seeking to enhance their training through scientific principles.

Unlocking the Science Behind Why Cats Love Catnip

Explore the fascinating science of catnip and its effects on felines, revealing how nepetalactol influences their behavior and even repels insects.

Understanding Dissociative Identity Disorder: An In-Depth Analysis

Explore the complexities of dissociative identity disorder, its historical background, symptoms, and treatment approaches.