0

i'm trying to make a list when users selects their fav links onClick ...

Any idea why this doesn't work? it will push values to state.array in console.log but JSX will not render in ul.li

import React, { Component } from "react";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      link: {
        name: "",
        type: "",
        size: "",
        tests: []
      },
      tests: ["1", "2", "3", "4"]
    };
  }

  componentDidMount() {
    console.log(this.state);
  }

  onClick = e => {
    const linktests = this.state.link.tests;
    console.log("clicked");

    linktests.push(e.target.innerText);
    console.log("link tests : " + linktests);
  };
  render() {
    const { link, tests } = this.state;
    const linktests = this.state.link.tests;
    return (
      <div>
        <div id="link">
          {linktests.map(stuff => (
            <ul>
              <li> {stuff} </li>
            </ul>
          ))}
        </div>
        <br></br>
        {tests.map(stuff => (
          <ul>
            <li onClick={this.onClick} value={stuff}>
              {stuff}
            </li>
          </ul>
        ))}
      </div>
    );
  }
}

hope someone can help :D <3 thanks

tafhim
  • 123
  • 9

1 Answers1

0

You need to set the new links to the state. Also use concat or slice on the original state array to avoid mutating it directly.

 onClick = e => {
    const linktests = this.state.link.tests.concat();
    console.log("clicked");

    linktests.push(e.target.innerText);
    this.setState({link: { ...this.state.link, tests: linktests});
  };
Clarity
  • 10,730
  • 2
  • 25
  • 35
  • rendering works , thanks. but it doesn't update the state in console log, why is that? – tafhim Feb 17 '20 at 17:29
  • @tafhim `setState` is async, so you won't see the changes in console immediately. For that you'll need to pass a callback to `setState`: `this.setState({link: { ...this.state.link, tests: linktests}, () => console.log(this.state.link))`. – Clarity Feb 17 '20 at 17:58