PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label jsx. Show all posts
Showing posts with label jsx. Show all posts

Wednesday, November 9, 2022

[FIXED] How to create a list by getting the ids of specific elements in React?

 November 09, 2022     dom, html, javascript, jsx, reactjs     No comments   

Issue

Guys I need your help with an issue. I am recently learning how to use React. The question is this: I have three h2 elements, each with a different id attribute. What I am trying to do is create a list consisting of as many "a" elements as there are h2 elements. Each "a" element should have the href attribute pointing to the respective h2 element.

I show you what I have tried to do. With the code I wrote the list remains blank.

import logo from './logo.svg';
import './App.css';
import { Link } from "react-router-dom";

function App() {
  const h2 = Array.from(document.getElementsByTagName('h2'));
  const list = h2.map(element => {
    return (
      <li key={element.id}>
        <Link to={`${element.id}`}>{element.innerHTML}</Link>
      </li>
    );
  })

  return (
    <div className="App">
      <h2 id="first">First item</h2>
      <h2 id="second">Second item</h2>
      <h2 id="Third">Third item</h2>

      <h4>List of h2:</h4>
      <ul>
        {list}
      </ul>
    </div>
  );
}

export default App;

Could you tell me what I should do or the concepts I should go to study?


Solution

There are two problems in above solution.

  • Fetching H2s before they render for the first render.
  • Missed appending # before redirection link for ID.

Here's the solution. I have used a tag instead of react-router's Link but it will work in similar pattern.

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [list, setList] = useState([]);

  useEffect(() => {
    // Added this in useEffect as we endup fetching h2s before they render if kept outside. Here they will be fetched post first render
    const h2 = Array.from(document.getElementsByTagName("h2"));
    const currentList = h2.map((element) => {
      return (
        <li key={element.id}>
          <a href={`#${element.id}`}>{element.innerHTML}</a>
        </li>
      );
    });

    setList(currentList);
  }, []);

  return (
    <div className="App">
      <h2 id="first">First item</h2>
      <h2 id="second">Second item</h2>
      <h2 id="Third">Third item</h2>

      <div style={{ height: "100vh" }}>Some space</div>

      <h4>List of h2:</h4>
      <ul>{list}</ul>
    </div>
  );
}

Here's a working example at codesandbox, I have added a large div in the center to make scroll visible. Please scroll down the example.



Answered By - Mehul Thakkar
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 8, 2022

[FIXED] why my component didn't re-render when the state change?

 July 08, 2022     class, javascript, jsx, reactjs, state     No comments   

Issue


the values of value 1 and 2 and 3 which stored in the props are Math.floor(Math.random() * 100) so what I want to know when I setState and the value of numQuestions , numCorrect change and the render method is being called as I know why this render didn't make the three values 1,2,3 reproduced again and their values change with each click of the two buttons .

class App extends Component {
      constructor(props) {
      super(props)
      this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
      this.state = {
        numQuestions : 0,
        numCorrect : 0,
      }
   }

   rightanswer= ()=> {
        if(this.proposedAnswer === this.props.value1 + this.props.value2 + this.props.value3){
          this.setState((oldstate)=> ({
            numCorrect : oldstate.numCorrect +=1 ,
            numQuestions : oldstate.numQuestions += 1 ,
          }))
        }else{
             this.setState((oldstate)=> ({
             numQuestions : oldstate.numQuestions += 1 ,
         }))
     }
  }

   falseanswer= ()=> {
         if(this.proposedAnswer !== this.props.value1 + this.props.value2 + this.props.value3){
           this.setState((oldstate)=> ({
               numCorrect : oldstate.numCorrect +=1 ,
               numQuestions : oldstate.numQuestions += 1 ,
           }))
         }else{
               this.setState((oldstate)=> ({
               numQuestions : oldstate.numQuestions += 1 ,
         }))
        }
      }

   render() {
      return (
          <div className="App">
            <div className="game">
              <h2>Mental Math</h2>
              <div className="equation">
                  <p className="text">{`${this.props.value1} + ${this.props.value2} + 
                   ${this.props.value3} = ${this.proposedAnswer}`}</p>
              </div>
              <button  onClick={() => this.rightanswer()}>True</button>
              <button onClick={() => this.falseanswer()}>False</button>
              <p className="text">
                 Your Score: {this.state.numCorrect}/{this.state.numQuestions}
              </p>
             </div>
          </div>
       );
      }
    }

  export default App;

Solution

Your component is re-rendering when the state changes. However, your props do not change because you are not passing in new props from the parent component, so value1, value2, and value3 remain the same.

If you want your values to change on a state change, one approach is to move all of your values to state, initialize them when the component mounts, and update them when your component updates:

  constructor(props) {
    super(props);
    this.state = {
      numQuestions: 0,
      numCorrect: 0
    };
  }

  componentDidMount() {
    this.generateValues();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.numQuestions !== prevState.numQuestions) {
      this.generateValues();
    }
  }

  generateValues = () => {
    const values = [...Array(3)].map(() => Math.floor(Math.random() * 100));
    const correctAnswer = values.reduce((a, b) => a + b, 0);
    const proposedAnswer = Math.floor(Math.random() * 3) + correctAnswer;
    this.setState({
      value1: values[0],
      value2: values[1],
      value3: values[2],
      correctAnswer: correctAnswer,
      proposedAnswer: proposedAnswer
    });
  };


Answered By - gloo
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing