Style selector for dynamic drop-down menus

import React, { Component } from "react";

export default class FontChanger extends Component{

    constructor(props){
        super(props);
        this.state ={
            selectedFont: "",
            currentFont: "",
        };
        this.handleFontChange = this.handleFontChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleFontChange(event){
        this.setState({
            currentFont: event.target.selectedFont,
            selectedFont: this.state.value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        this.setState({ currentFont: this.state.selectedFont });
    }

    render() {
        return(
            <div>
                <form onSubmit={this.handleSubmit}>
                    <h1 style={{fontFamily: this.state.currentFont }}>Yuh Yeet</h1>
                    <select onChange={this.handleFontChange}>
                        <option value="Anton">Anton</option>
                        <option value="Calistoga">Calistoga</option>
                        <option value="Fira Sans">Fira Sans</option>
                        <option value="Noto Serif">Noto Serif</option>
                        <option value="Quicksand">Quicksand</option>
                        <option value="Ubuntu">Ubuntu</option>
                        <option value="Times New Roman">Times New Roman</option>
                        <option value="Titillium Web">Titillium Web</option>
                    </select>
                    <button type="submit"> Change </button>
                </form>
            </div>
        )
    }
}

I'm having trouble changing the inline style of the h1 tag with a font selected from my dropdown menu. I've imported all fonts into my index.html from Google Fonts, so that shouldn't be an issue. Could it be an error in how I'm using setState or accessing the state values?

Answer №1

The following code functions properly. Here are a couple of points to note:

  • It is correct that the onSubmit handler is not necessary as mentioned by Taki. However, if you do not use it, the font will change as soon as it is selected, rather than when the "change" button is clicked. Additionally, in Taki's solution, the fontHandler function would not provide the expected result in setting the state. If that function was utilized, the state would need to be set to current: value.target.value
  • When using the setState(), there are two considerations. 1 - Refrain from referencing the current state; instead, use prevState. State updates are sometimes grouped together, leading to potential errors. 2 - Avoid referencing the eventHandler for two reasons. Firstly, it may not recognize what you are referring to. onChange and onSubmit are not functions defined within your component, but rather attributes to <form> and select respectively. Secondly, it is best practice not to reference functions within the state. Create the function outside of the state object and call it to set the desired state changes.
  • I have initialized the state with the first select option. This won't impact the functionality of your app, but it will enhance the user experience if the default font is not set to Anton.

Furthermore, consider exploring Hooks and Arrow functions. They can simplify your work and streamline your code.

I trust this breakdown sheds light on why your code may not be functioning as intended. Yeet yeet.

export default class Fonts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedFont: "Anton",
      displayedFont: "Anton"
    };
    this.fontHandler = this.fontHandler.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  fontHandler(event) {
    const font = event.target.value;

    this.setState({
      selectedFont: font
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    this.setState(prevState => ({
      displayedFont: prevState.selectedFont
    }));
  }

  render() {
    return (
      <div>
        {console.log(this.state)}
        <form onSubmit={this.handleSubmit}>
          <h1 style={{ fontFamily: this.state.displayedFont }}>Yuh Yeet</h1>
          <select onChange={this.fontHandler}>
            <option value="Anton">Anton</option>
            <option value="Calistoga">Calistoga</option>
            <option value="Fira Sans">Fira Sans</option>
            <option value="Noto Serif">Noto Serif</option>
            <option value="Quicksand">Quicksand</option>
            <option value="Ubuntu">Ubuntu</option>
            <option value="Times New Roman">Times New Roman</option>
            <option value="Titillium Web">Titillium Web</option>
          </select>
          <button type="submit"> Change </button>
        </form>
      </div>
    );
  }
}

Answer №2

Your code has a few issues that need addressing. The select element's onChange attribute should point to the function fontHandler, which will update the state to set the value of current:

<select onChange={this.fontHandler}>
  // ...
</select>

The fontHandler function should look like this:

fontHandler(value){
  this.setState({      
      current: value
  });
}

No need to submit the form.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unusual Conduct when Interacting with ContentEditable Text

Looking for help with a strange issue that I can't seem to figure out. Hopefully someone has encountered this before and might have a solution. In my Angular app, I'm using a contenteditable <div> for inputting content, which is working fi ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

Struggling with implementing Mobile Navigation menu

I'm struggling to implement a mobile menu for my website. After adding the necessary code, when I view the page in a mobile viewport, all I see are two sets of periods ("..."). However, unlike in the code snippet provided, the list does appear on the ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

embedding HTML code directly into an iframe

Can HTML be directly inserted into an iframe within my HTML template? Would the following code be considered valid? <iframe> <html> <head> </head> <body> <p>Hello world</p> </body> ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...

After changing pages, the checkbox's state is reset to empty

I am currently working with an array of objects structured as follows: const columns = [ { key: "Source_campname", title: "TS Camp Name", customElement: function (row) { return ( <FormControlL ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Implementing the Delete feature using AJAX in this specific scenario: What is the best approach?

My website utilizes PHP, Smarty, MySQL, jQuery, and other technologies. It involves fetching a large amount of data from the database and presenting matching question ids on a webpage. This process of retrieving and displaying the matching question ids for ...

Tips for styling tooltips in rc-slider

I am currently using the react library rc-slider and I am looking to add a tooltip feature to display the current value. I found guidance on how to do this from a post on the rc-slider GitHub page. However, I encountered an issue where my slider position b ...

Can you tell me the specific location in the CSS where this logo image is defined?

I've been working on a website at http://onofri.org/WP_BootStrap/ and I'm facing an issue. When using FireBug, I can't seem to locate where in the CSS the image logo.png is defined (this is the small image in the upper-left corner of the the ...

Utilize PHP's file_get_contents to trigger the Google Analytics tracking pixel

For certain goals I have set up in Google Analytics, I am unable to use the JavaScript tracking. Instead, I am interested in achieving the same result by making a call with PHP. One solution that seems straightforward to me is to invoke the URL of the tra ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

Empty Canvas: Google Charts Graph Fails to Populate

I am currently using mysql, php, and javascript to display a curve chart. The issue I am facing is that the chart appears blank. google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLo ...

Step-by-step guide to selecting a specific point on an HTML5 canvas using Python's selenium webdriver

Looking to automate interactions with a simple HTML5 application on a website using Selenium webdriver in Python with Firefox on Linux. The challenge is clicking a button on an HTML5 canvas, then dragging one or two objects around the canvas post-button cl ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

Using functions like nl2br() for new line breaks, preg_replace for replacing patterns, htmlspecialchars() for encoding special

I've reviewed all the answers on this topic, but I'm still struggling to find the correct method for sanitizing data. My task is to enter: <?php echo 'yes'; ?> <?php echo 'yes' ?> into a text area, submit it in ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Incorporate Margins for Table Cells in Outlook (HTML Email)

I'm currently in the process of creating an email newsletter and testing it out on Litmus. Here's how the newsletter design should appear (refer to the image below): Although I understand that it may not look exactly the same on Outlook, is the ...