0

I am trying to build a small app that takes user-inputted text and highlights the consonants and vowels in each word inputted by the user.

I am unsure how to add the new span element that gets created via a function call into the actual DOM (I am new to react).

Here is where I have gotten to:

import React from "react";

import "./AnalysisArea.css";

const AnalysisArea = (props) => {
  const graphemes = props.text.split("");
  console.log(graphemes);
  const analyseText = () => {
    const getClass = (character) => {
      if (["a", "e", "i", "o", "u"].includes(character)) {
        return "vowel-class";
      } else {
        return "consonant-class";
      }
    };

    //the span
    return graphemes.map((character, i) => {
      return(
      <span class={getClass(character)}>
        {(i === 0 ? "" : ",") + character}
      </span>
      )
    });
  };

  return (
    <div className="analysisframe">
      <button onClick={analyseText}>Analyse</button>
      <div>
        <p>{props.text}</p> //this is where the span should go 
      </div>
    </div>
  );
};

export default AnalysisArea;

1 Answer 1

1

It is very common to use Array.prototype.map() to render React elements. I would suggest something like this:

import React, { useState } from "react";

import "./AnalysisArea.css";

const getClass = (character) => {
  if (["a", "e", "i", "o", "u"].includes(character)) {
    return "vowel-class";
  } else {
    return "consonant-class";
  }
};

const AnalysisArea = (props) => {
  const [showAnalysis, setShowAnalysis] = useState(false);

  return (
    <div className="analysisframe">
      <button onClick={() => setShowAnalysis(true)}>Analyse</button>
      <div>
        <p>
          {showAnalysis &&
            props.text.split("").map((character, i) => {
              return (
                <span key={i} class={getClass(character)}>
                  {(i === 0 ? "" : ",") + character}
                </span>
              );
            })}
        </p>
      </div>
    </div>
  );
};

export default AnalysisArea;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.