Is React.js so necessary in real world?

why in hell tutorial show harder way to Onclick?

I don’t know what tutorial you’re speaking of, so I’ll just use the code you put up

Ok, a few things. First, you have to stop trying to apply what you learned with jquery to react. React is a different way of programming. So you have to get used to reading the documentation to find your solutions.

Now, there are two different types of react components, and you will see them called different ways. There’s functional (dumb, presentational, stateless), or class (smart). https://reactjs.org/docs/state-and-lifecycle.html

Using your examples:

  • Functional components don’t carry state, so they have no knowledge of anything except what you pass in. This is why we call them dumb components
function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.'); // <-- This is fine since there is no state
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}
  • Class components can carry state
class Welcome extends React.Component {
constructor(props) {
    super(props);
    this.state = {}; // <--- This is the component's state. And can only be used in 
                    //  in a class component
  }

  handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

 render() {
   return (
    <a href="#"
     onClick={this.handleClick} // <-- we now have to call the class method with "this"
    > 
      Click me
    </a>
  );
 }
}

If you don’t need state, always use a functional component.

Think of classes as objects that have a life. They are born, have knowledge of themselves, can act independently, and when they die, they take all that knowledge with them. You can read up on classes here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Now, you want to know the id of the element that was clicked, right? In React, you can attach any prop you want to the dom elements. So you can just do (with a functional, stateless component): https://reactjs.org/docs/components-and-props.html#rendering-a-component

function ActionLink() {
  function handleClick(id) {
    e.preventDefault();
    console.log(`The link for id ${id} was clicked.`); 
  }

  return (
    <a href="#" 
       id="some-id" // <-- custom prop; get the id somehow
       onClick={() => handleClick("some-id")} // <--- pass the same id to the handler
    >
      Click me
    </a>
  );
}

This is how you know which element was clicked. The only issue would be that a new function is created for each render cycle. You may hear alot about that. But for now, I think you should just try to get a grasp for react before worrying about that, since it only matters on really complex, dynamic apps.

If you’re still struggling with react, these are the two courses that cleared it up for me.

I have no connection to the instructor, and I watched last year’s editions, but I didn’t need any other tutorials after watching them. He explains things very clearly and simply.

I recommend watching each section first, and then trying his examples on your own, instead of coding while watching. This way you have an idea of what to do, but still have to figure it out yourself. Then come back to freecodecamp and build their example projects for more practice.

They’re on udemy, so they usually have sales for $10. Obviously wait for those or you’ll pay $140. lol

www.udemy.com/react-redux-tutorial/

they have confusing examples.
As I understand that props should have anything name I really don’t understand why they created if all should be created without that and normal passing data had know. it;s only complicated solutions. I don;t like so I don’t used it.
And that state why, they not say you cannot passing data trought setState, it’s state is been updated when all function done and second you sometimes must clone array because it,s not rendering.

As I understand that props should have anything name I really don’t understand why they created if all should be created without that and normal passing data had know. it;s only complicated solutions.

They created it because each element already has certain props available, like onClick, onHover, etc. They are called syntheticEvents because react wraps all the native dom events in order to ensure data updates properly.

I don;t like so I don’t used it.

Well that’s not really an option, is it?

And that state why, they not say you cannot passing data trought setState, it’s state is been updated when all function done

You don’t pass data through setState, you pass data through props. setState does exactly what it says, it sets the components state.

and second you sometimes must clone array because it,s not rendering.

Are you always updating your state using setState? The only reason react should not know that it has to re-render is if you manually update state. You must always use setState.

Have you looked into the videos I linked? You seem to be having trouble understanding their docs. But those videos will definitely help clear things up. If you keep fighting against the paradigm, you’ll never learn it.

I don’t read stupid manuals, because their examples of solutions work only in the the current solutions, not when you use them in codes. Stack-overflow is popular because creators always hidings problem of their work. And React have many. It’s nowhere sayed don’t save data into state to other functions, because actually nothing update. I don’t used props, traditional function(value){value} is know approach if that work I do not changed. the explanation of props they are outside const of whole code, passing through DOM . I don’t called props in events, its values and always be the autors only mess the naming confused so I hated them for that. it’s just values constants. We don’t used the frequent named we used new names. it looks like we are creating whole coding world.
So there only one new the state and you need declare as that say with constructor, just type state{}. So why they not focus to state explanations.
The Game of life bring these problems. If you start with creating random and then call other function play the updating of (rowcolarr ) did not happened and the refreshing of the elements also not. If you create g2 as g its not working, I today don’t understand why that work if the array clone only with stringify and parse the same arr. In VBA or JS is nothing similar happened.
if don’t create other function refresh array and pass div elements in first function as true and false, the updating of this.setState({rowcolarr, generation: this.state.generation + 1 }); do not work in play and the generations refreshings.
the freecodecamp solutions have 237 lines my have 137 lines and should be 30 less if I know how to solve the up said.

play = () => {
      let g = this.state.rowcolarr.slice();
      let g2 = this.arrayClone(g);
     /* 123
        456
        789  */
      for (let i = 0; i < this.state.rows; i++) {
        for (let j = 0; j < this.state.cols; j++) {
          let count = 0;
          var rowup =i -1;
          var rowdown = i + 1;
          var oneleft =j - 1;
          var oneright =j + 1;
          var live =g[i][j][1];
          if (i > 0) if (g[rowup][j][1]) count++;//2
          if (i > 0 && j > 0) if (g[rowup][oneleft][1]) count++;//1
          if (i > 0 && j < this.state.cols - 1) if (g[rowup][oneright][1]) count++;//3
          if (j < this.state.cols - 1) if (g[i][oneright][1]) count++;//6
          if (j > 0) if (g[i][oneleft][1]) count++;//4
          if (i < this.state.rows - 1) if (g[rowdown][j][1]) count++;//8
          if (i < this.state.rows - 1 && j > 0) if (g[rowdown][oneleft][1]) count++;//7
          if (i < this.state.rows - 1 && this.cols - 1) if (g[rowdown][oneright][1]) count++;//9
          **if (live===true && (count < 2 || count > 3)) g2[i][j][1] = false;**
**          if (live===false && count === 3) g2[i][j][1] = true;*
                  }
      }
       this.refresharray(**g2**);
  }
  refresharray= (**rowcolarr** ) =>{
        
             for (let indexr = 0; indexr < this.state.rows; indexr++) {                                        
               for (let indexc = 0; indexc < this.state.cols; indexc++)   {                  
              var    boo  =rowcolarr[indexr][indexc][1]   ;               
                   var onoff = 'box '+boo; 
                  rowcolarr[indexr][indexc][0]=<div className={onoff} key={indexr+'_'+indexc} id={indexr+'_'+indexc}  /> ;
                           
                  }              
               }
                **this.setState({rowcolarr,**    
        generation: this.state.generation + 1  });   
    
             }

             arrayClone= (arr) => {
              return JSON.parse(JSON.stringify(arr));
            }

Thats why i like vue :slight_smile:

2 Likes

It seems a law of the universe - anytime you discuss view engines, it is only a matter of minutes before some people will get in it to convince you to switch to Vue. [rolls eyes]

But that does not mean that all criticism is good - it must be informed and constructive. There also seems to be a strange feature of human nature that the more popular thing is, the more people enjoy trying to complain about it.

Look, you don’t like React - we get it. Then don’t use it. But be aware that it is part of the FCC program. Many of us find it incredibly powerful and useful and conceptually helpful. But if you don’t like it, that’s fine. Use something else. There are many jobs that don’t need React. But FCC is based on the MERN stack, so that is what we learn here.

That is certainly true. It’s a matter of degrees. Yes, there are apps that a simple enough that React would be a hindrance. Apps that don’t need JS? There aren’t many apps on the web that don’t need JS. Maybe some don’t need it but benefit from it greatly. I don’t think anyone is going to get a FE job if they don’t have JS.

No, “everyone” is not using it “without thinking”. Many of us are putting a great deal of thought into the tools we use and we find the one-way data binding, component modularization, and state management to be extremely useful on some apps, especially as projects grow.

This thread is starting to get off topic. If we have specific coding questions, those should start in their own threads. This topic was about React in the real world.

2 Likes

And this is why you’ll continue to struggle with these higher level abstractions. RTFM is a very common response on stackoverflow

Stack-overflow is popular because creators always hidings problem of their work.

Have you ever asked a question on stackoverflow? Because they very first thing you’ll be asked is for a sample of your code attempts. Stackoverflow is popular because it’s impossible to know everything. It’s unfortunate that lazy devs take advantage of it.

It’s nowhere sayed don’t save data into state to other functions, because actually nothing update.

Since you don’t read manuals, I’m not surprised you didn’t find this https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly

See the hash? It says “using state correctly”

I don’t used props

Do you also demand that javascript and jquery cater to how you want to use it? Seriously. I’m beginning to think you’re not interested in actually learning, just complaining it’s not how you want.

it looks like we are creating whole coding world.

Exactly. And React doesn’t hide that fact from you. https://reactjs.org/docs/thinking-in-react.html

The truth is that whether you use jquery, react, angular, vue, etc…you will have to learn their way.

So there only one new the state and you need declare as that say with constructor, just type state{}. So why they not focus to state explanations.

Honestly, if you don’t read the manual no one can help you. Here it is again https://reactjs.org/docs/state-and-lifecycle.html

if don’t create other function refresh array and pass div elements in first function as true and false, the updating of this.setState({rowcolarr, generation: this.state.generation + 1 }); do not work in play and the generations refreshings.

I don’t follow what you mean. But looking at your code you have a fundamental misunderstanding about updating state and rendering in react. I said it earlier, but I’ll highlight it for emphasis

Only update your state to the FINAL DATA.
Then let REACT handle the final DOM representation

What you did is setState to final html representation in your loops. DO NOT DO THIS. Any html elements need to be rendered by react inside the render method (or just return if stateless). So, your example should really be closer to this. Since I don’t have access to your full code, I can’t verify if it works completey. But it should hopefully give you some insight.

class App extends React.Component {
  constructor(){
    super()
    this.state = {
      rows: [],
      cols: []
    }
  }

  play = () => {
    let g = this.state.rowcolarr.slice();
    let g2 = this.arrayClone(g);

    ...

    this.setState({rows, cols})
  }

/** 
* Since what you want inserted to the dom is a list of elements e.g a bunch of divs
* YOU MUST RETURN AN ARRAY OF ELEMENTS
* 
* In react you can only return
*   1. a react element
*   2. an array of element(s)
*   3. a string (React 16)
*   4. a react fragment (React 16)
*
* You will usually return 1 element or an array though
**/

  render() {
    return (
      // returns final, nested array. 
      // React will figure out how to render the actual html
      this.state.rows.map((row, indexr) => 
        this.state.cols.map((col, indexc) => {
          const boo = row[indexc][1]; // Not sure what you want here
          const onoff = 'box ' + boo;
          return <div
            className={onoff}
            key={indexr + '_' + indexc}
            id={indexr + '_' + indexc}
          />
        })
      )
    )
  }
}

// If you don't want to, or don't understand the map function
// you could do it in a loop.
// But this is not what others reading your code will expect

render() {
    const finalArr = []

    for (let indexr = 0; indexr < this.state.rows; indexr++) {
      for (let indexc = 0; indexc < this.state.cols; indexc++) {
        var boo = this.state.rows[indexr][indexc][1];
        var onoff = 'box ' + boo;
        finalArr.push(<div className={onoff} key={indexr + '_' + indexc} id={indexr + '_' + indexc} />);

      }
    }
    
    return finalArr
  }

I don’t mind helping you through this, but if you keep saying things like “I don’t read stupid manuals”, I’ll have no choice but to think you’re not serious. If you are serious, then I won’t give up until you get it :slight_smile:

3 Likes

Thats why i like vue :slight_smile:

And yet he will still have to learn vue’s abstraction. So not really solving his problem, right?

I don’t need read the manuals I am different I must understand the autor, how he thinking which roads he goes before and than i know how to handle the unknown. And that is five points in websites, nobody had so many times. It’s ridiculous, there could be whole react described in five lines. Some people have the gift to write and some not and these guys have not. If there is not props as I said before, they doesn’t handle as problem they are updated asynchronously and have place for said state are not usual variables.


I do not in code call setState Inside the loop.
Yeas, sometimes I put there if I cannot move and I don’t get satisfying answer. sometimes I am angry with arrogance of not answer the point of questions, because I don’t ask how but why? and only person who is like me can understand my frustrations.
https://stackoverflow.com/questions/50198006/how-to-add-a-href-link-in-jquery-with-variable
I don’t get the answer. I always get something like don’t ask do as is written. There is very little people whom had understanding and sometimes kick me, but o.k. that put me to another level. The answer I found later is satisfying is something with jquery which is inherited. But finally get How to handle the single qoutes. You cannot find on internet how used them and with double qoutes either, I have similar problems in vba. You must experimenting to find out.
I really surprised the programators write like this chapters
State Updates May Be Asynchronous
In the examples is: do not use the state and props together. There is nothing said about don’t use state as variables is always wait until all functions in chain done. It’s deformations because I 22 months create the comma and therefore I must study the syntax. They never heard about counter pyramide of informations?
The autors barely even don’t know what they created, therefore theirs manuals is stupid, I found out after readings five words, so I don’t read. And there is something with type of font on that websites. I am surprised how they with current knowledge and tools of behaviour visitors create site like that. They even use the bulleted list.
I first use the For cyclus in render, but then is on stack the way if you want use For instead of Map use the Array and setState.
Even the Microsoft have get it after he released the XAML, but for some people it’s to late, they lose the writes.
I f their invest to the explanations in short A4 difference and ways from VBA instead the marketing, that should not happened.

ubodrinka, I think you have some issues here.

First of all, I might suggest that part of the problem is your English. Please don’t take this as an insult. I study Spanish and French and would hate the idea of having to deal with forums in those languages. Your English is much better than my Slovakian. I thank you for participating in this forum in a language that is not your first. But … if you’re not understanding things, it may not be that it’s not well written, it may be that you just aren’t understanding. I understand it’s difficult, but it might not be the manual’s fault. (But I agree that there is a lot of bad writing and documentation out there.) We’re perfectly willing to be patient with your language difficulties, but you also need to be patient.

Reading manuals is an important part of web dev. These libraries, frameworks, and api’s. are constantly changing and how they interact keeps evolving. Most of us get that information from reading. Of the manual by the creator is the most important source. If you want to be a good developer, you’re going to have to read a research.

You seem to not like Stack Overflow. I can feel your pain - I’ve had some bad experiences there too. Yes, they can get angry if you don’t ask the question the right way. Yes, they can be hostile. But they are a collection of very talented devs that can give great information.

Looking at some of the coding examples, I might suggest that you are trying to learn too much, too fast. Make sure you understand core concepts. Work through the React material, step by step. If you have something that confuses you, please come and ask. Make each question separate and very specific with and example if possible. No matter what question you have, there are also 10 more people who are also confused but are too afraid to ask.

Yeah, it’s visible you are educated. It 's good to read something with empathy. The law is also program, have a readable CSS styling and have a terminology, without knowing it you cannot understand the point. In law principles is not the same as principle in common use. Is like people drive always right, but that doesn’t mean you shouldn’t sometimes left. But if you understand there are the basics variables you can speech or understand any law systems. You don’t need to study from beginning, but learn the differences. The capacity of brain is limited. What I criticize the react is not focused in explanation on main advantage, the rendering. They focus on props, what is not needed, when you come from JS or JQuery and you want really fast convert your app. It is unnecessary loads.

That is why react exists.
it should be writing as:

  1. HTML rendering back-end when refreshing the pages,
  2. JQuery can anytime, but whole site
  3. React the any elements and for the you need declare your variables or arrays in state{variable: 0} and express in curly brackets between elements inner the render return declarations. The state is asynchronously it’s update on elements when is most optimal, not when you sent back with this.setState({variable})
    In five lines I described the whole concept
    Than should be a warning about the diff className instead of class and style declare in curly brackets.
    And finally how to convert For cyclus
    A. to map in render
    B. create functions with state array which one you expressed as
    {array}

    and one image where is all .

    I am sorry about my English skill, but I takes it as writing practice. It dependents how the critics are and you make it well. What happened if instead of logo after you call NPM start are basics principles showing?
    I think it is man ego, that someone should write better and secondly they don’t have an critical distance. There are plenty of competitions, who write the best manuals.
    The props like let [] = something is pretty featured, why if there is common and shorter way? I am really curious if they back after five years to theirs code if they still understand them.
    And fro me the props are properties and I imagine the something with paint or art, so: colors, style, font. As son of teacher Slovak’s languages I dislike if someone tell me the props are constants, is it? Tear my ears.

const has nothing to do with React. It’s a part of ES6 (newer version of JavaScript), along with let. Generally, it’s better to declare variables with const and let because they’re block-scoped rather than function-scoped, which makes them more intuitive.

For example, for (var i = 0; i < 10; i++) exposes i to the scope outside the for loop, which probably isn’t what you wanted. Using let removes this problem. This becomes very clear when you add setTimeout(() => console.log(i), 1000 * i) to the loop. If you used let, you get the results you were probably expecting (logs 0 after 0 seconds, 1 after 1 seconds, all the way up to 9). If you used var, however, 10 is logged 10 times at 1-second intervals.

As for why to prefer const to let, it’s the simple principle of restricting the ways in which future-you or someone else can write buggy code in the future. Most of the time, when you declare a variable, you don’t actually want it to change within its current block scope. Allowing it to do so is just a needless risk that will lead to confusing and time-consuming bugs to be fixed later.

For the same reason, this:

Is actually a feature. During development, you want your app to crash when there are problems, because you can fix them right at that time. If the app just guesses what it thinks is the best thing to do, you only become aware there’s a problem much later (perhaps when you’re adding a new feature a few months down the line, or perhaps your end users encounter problems in a few edge cases that you didn’t test for). It’s much quicker, easier, and cheaper to fix bugs sooner rather than later.

I have to admit, I started out as a React sceptic as well. I didn’t find it intuitive and felt it was overcomplicated. But these days, whenever I start up a personal project, I generally start with create-react-app. If it’s supposed to be a very small, simple project. I usually don’t bother and go the vanilla JavaScript route. But the interesting thing is, about 50% of the time I don’t use React, I end up wishing I had once the app reaches even a moderate amount of complexity (and sometimes end up migrating the project over to it).

Ok, I’m going to answer your questions here one last time because we’re now getting off topic. If you want to continue in pm or pair programming, I’m happy to help you out with this or any other question. I don’t mind if your english isn’t that good.

Don’t give up. I had 0 programming experience last year when I started. You just gotta stop trying to force a different way of thinking than react requires.

First, please, please, please use https://codesandbox.io. You’re making your life much harder than it needs to be. Here are the top reasons to use it instead of codepen

  1. code completion
    • it really helps to have these types of hints. When you get to the real world, you’ll be using webpack and a much more advanced IDE, so you may as well get the benefit now
  2. React hot-reload error traces
    • codepen doesn’t give you any idea why the code failed. I rewrote your example and couldn’t do it without it.
  3. live linting
    • you won’t believe how many times your bug is caused by a simple writing error
  4. live coding
    • new feature for remote pair programming

Seriously, use codesandbox. Here’s an error trace to show you.

React Error trace. Now how great is this?


Now, there are 2 reasons that your code wouldn’t re-render on setState.

  1. because you are storing react elements in the state. Your state should always be serializable. That means only javascript primitives. No methods, classes, etc. – Only Arrays, objects, strings, numbers, booleans, etc.

    • to hack around this, you had to call refreshArray. In that function you re-wrote the react element which caused a render. Remember, react only renders what’s different, and you essentially changed it for react. That’s a no-no. You must let react construct and render the dom
  2. You were using array.splice(), but that only creates a shallow copy of the array.

    • this means that when react checks oldArr === newArr, it will always return true.

Ok, now here is a working sample of your code. https://codesandbox.io/s/5w1jywyvl4

I made 4 main changes:

  1. I abstracted the buttons into a functional (stateless) component. This hopefully shows you how powerful react can be once you use components. Also, it will show you why props exist in the first place. One of the benefits of react is that you can reuse components. And now, you could use these buttons with it’s styling in other places, keeping your code DRY.

  2. I also rewrote your random function to create a matrix of objects instead of elements. These objects have all the relevant info for the render function to create the dom. It looks like this

rowarr.push({
          bool, // <-- boolean flag setting the cell on/off
          key: `${indexr}_${indexc}`, // <-- using es6 template strings
          id: `${indexr}_${indexc}`
        });
  1. I added a flipCell method to create a new object
    • array.splice() creates a shallow copy, so the objects keep their references. This will mutate only the changed ones
flipCell = (obj, bool) => Object.assign(obj, { bool });
...

let currCell = g[i][j];

...

if (live === true && (count < 2 || count > 3)) {
  currCell = this.flipCell(currCell, false);
}
if (live === false && count === 3) {
  currCell = this.flipCell(currCell, true);
 }
  1. the render method for the cells looks like this
const { generation, cols, rowcolarr } = this.state;

...
<div className="App grid" style={divStyle}>
  {rowcolarr.map(cells =>
    cells.map(cell => (
      <div className={`box ${cell.bool}`} key={cell.key} id={cell.id} />
     ))
   )}
</div>

Hopefully that helps you some. Like I said earlier, we have gone way off-topic now. So if you want to continue, we should do so in private messages.

Example link again so you don’t have to scroll: https://codesandbox.io/s/5w1jywyvl4

lubodrinka,

I really think you just need to back up and work on basics. Learn to walk before you try to fly. I know that you get frustrated. Yes, this is frustrating. But that is why it is a good paying field. Go back, work on fundamentals. Go slow. If you have a specific question, then ask. Don’t advance until you understand.

1 Like

Putting the <div/> into array, it’s actually not my fault.
1 looks something how to keep For instead of map.
2. My solution passing <div /> it’s working because, it takes as props, they cannot render because the state and props update async. When I passing it in next passing I accidentally synchronized them or I try to change the “constans” the props second time and that should be why is not allowed put the components in a state. It’s probably working in random because I first assigned the props . it’s like const g = <div/> and try to assign g = <div />.
That is diff how and why? And really if in React are not props it will possible. If someone create something like jquery the react minified/core(hacked) version that will be powerfull and you should render array directly.
3. the debbuger VS code say: If you meant to render a collection of children, use an array instead.
in div. They use bad words.
After the find the better manuals in webarchive and there is described better as current web. look down . What Shouldn’t Go in State?


for others


3 ok sandbox is allowed in the new freecodecamp rules.
4. it’s should tricked if the function is return or the map function and put in the variables let or const…and then render it between DIV elements as not array, but single line.
5. you said the buttons it’s powerful, but actually the code is longer. And the react buttons are bootstrap 3.0 so that should be why facebook looks bad and the buttons are usually one in the site elements and not get the web render faster, because it is promile and I think it’s not good way. But that is life, there are many crossroads as Netscape webfonts.

Check your inbox. I’ll answer all your questions in private messages from now on.

Have you ever asked why that happen?

I think its all related to the learning curve.

I was porting some of my codeigniter personal projects to laravel when i saw some videos about vue made by Jeffrey Way that made me fall in love with this lib.

Don’t get me wrong,I’m not an evangelist of the vue lib. I’m just a hobbyist coder , by the time of FIDO NET, if someone knows something about it, that doesn’t look at all for a job in this field.

If i will do it, i will loose all my joy for coding and learning new things .

1 Like

I just look at VUE sites it’s looks like I am invented what actually someone created.
That is the easy approach.

@sorinr, @lubodrinka Exactly. Vue was created with the beginner in mind. But when you need a more powerful and dynamic structure to your sites, you’ll still have to drop down to render functions, and even jsx to get the job done.

Vue recommends using templates to build your HTML in the vast majority of cases. There are situations however, where you really need the full programmatic power of JavaScript. That’s where you can use the render function, a closer-to-the-compiler alternative to templates.
https://vuejs.org/v2/guide/render-function.html

So the argument can be made, and very well, that most devs promoting the use of react just have higher ambitions for where they want to see the web go as far as apps. And that is more highly dynamic and interactive, which requires javascript.

So while vue is easier to start with, it sure isn’t easier for more complex apps. You’ll still have to become familiar with vanilla javascript structures like classes, closures, instances, etc.

Vue is the glue between jquery and dynamic apps. And I’d say a great place for beginners.

But if you know you want to go complex and rely on javascript from the get go, then why prefer vue when it’s main selling point is the simplicity of it’s html templates? The learning point argument fails at this stage.

1 Like