Alewa's avatar
Level 2

react and html array issue

When I write this html code in react and I use the [ ] after name attribute, I am not able to enter anything in my input field, but the moment I remove the [ ] from the name attribute, I am able to enter something into my input field but I get this error foreach() argument must be of type array|object, string given for not adding the [ ] next to my name attribute in input field. example

AddProduct.jsx file

<div>
                                            <input
                                                type="text"
                                                className="block w-full border border-gray-300 px-4 py-3 text-gray-600 text-sm rounded placeholder-gray-400 focus:border-primary focus:ring-0"
                                                placeholder="Size"
                                                name="size[]"
                                                onChange={handleInput}
                                                value={
                                                    productAttributeInput.size
                                                }
                                            />
                                            {errors.size && (
                                                <p className="text-red-600">
                                                    {errors.size[0]}
                                                </p>
                                            )}
                                        </div>```
so the error is at the name="size[ ]" bcos it did the same thing in my Thunder client app when I was testing the api, but the moment I added [ ] next to my name attribute, everything worked fine. any help?
0 likes
15 replies
Tray2's avatar

Shouldn't these two attributes be wrapped in double quotes?

  onChange={handleInput}
  value={ productAttributeInput.size }
1 like
Tray2's avatar

@jlrdw Not sure, I don't use react at all, I find it more complex than it really would need to be. I know enough JavaScript to make the things I need without pulling in a lot of packages and frameworks for the few js needs I have. Maybe @sinnbeck has an idea, he uses React if I remember correctly.

JussiMannisto's avatar

@Tray2 I was commenting on the double braces. There are no double braces in React (which uses JSX).

I don't use react at all, I find it more complex than it really would need to be.

I don't think you've understood the point of React. This is like saying Laravel is more complicated than it needs to be because you could just write small PHP scripts.

It's not an apples to apples comparison. React isn't a helper library. It's a completely different approach for building SPAs.

React doesn't matter for CRUDs with minimal JS, but it makes building UIs with any complexity a lot easier. And the virtual DOM is a big deal when there's a lot going on.

It's not perfect, but it's a whole lot better than the old jQuery hell.

Tray2's avatar

@JussiMannisto You misunderstand me, what I meant was that I feel that React, and most other JS frameworks, add a lot of complexity to your code. You can't compare it to a framework like Laravel, Laravel helps you write simple, beautiful, and maintainable code, while react makes you to do a lot of not simple, beautiful, or maintainable code (imho) to make things work. It could be that I don't know React or any of the other ones, but the feeling I get when looking at the code compared to a simple JS function is not a pleasant one.

Then we have the fact that the package managers for JS are really bad, and you also need to clean your code, and assemble it to even make it work. And don't get me started on TypeScript and the need to convert it to JS before you can even run it. The JS community has gone haywire when it comes to their infra structure. KISS does not apply. For me JavaScript is something you run in the browser, not on the server, the server is in my opinion much better served with a language that was designed for it from the beginning.

In most cases plain old JS would be enough for most sites, and adding 200Mb of node modules to solve something you can do with a few lines of regular JS, isn't really the way to go in my opinion.

There are valid use cases for these JS frameworks, but I think people are reaching for then long before they actually need to, and then after a while they are too tightly coupled to it that they have problems to separate the concerns. I much prefer to have a dedicated backend that handles all the business logic, and then let the frontend handle the visual part client side.

And yes, before you ask, I despise jQuery as well. Don't get me wrong, it served it's purpose back in the day during the Browser Wars, and the time of IE 5, 5.5, 6, 7, 8, and it did it with flying colors, it filled a need, but today the JS has evolved so much, that there isn't really a need to use it anymore.

The fetch APi and Async Await are two of those things that can be used instead of jQuery.

Here I am rambling on about things not really related to the thread, but I felt I needed to make my view clear on the subject.

To make it short and simple, I like to write my JS as close to as possible to the way I write my PHP.

It's not an apples to apples comparison. React isn't a helper library. It's a completely different approach for building SPAs.

I know it's not, but I think it should be.

1 like
jlrdw's avatar

@Tray2 agree With grabbing unnecessary frameworks because they are new. I just want to add that I used fetch js for a while then I tried axios js and I really do like axios js.

And no you do not need to use npm to install it.

So I mostly use plain javascript and axios now. @tray2 I would still use jquery over some of these new frameworks that change every 4 to 6 months. The maturity of javascript like you mentioned makes that's unnecessary.

1 like
Tray2's avatar

@jlrdw Axios is really sweet, but for most of my cases fetch is just fine :)

1 like
JussiMannisto's avatar

@Tray2

You misunderstand me, what I meant was that I feel that React, and most other JS frameworks, add a lot of complexity to your code. You can't compare it to a framework like Laravel, Laravel helps you write simple, beautiful, and maintainable code, while react makes you to do a lot of not simple, beautiful, or maintainable code (imho) to make things work. It could be that I don't know React or any of the other ones, but the feeling I get when looking at the code compared to a simple JS function is not a pleasant one.

The opposite is true. JS frameworks add dependencies (as does Laravel). But they also add structure and make complicated UI code more maintainable.

Comparing React to a simple JS function isn't right. React is not about sprinkling in JS code. If you use it, you write your entire UI with it. That said, writing React isn't complicated. Let's look at some examples:

function foo() {
	console.log('Hello, world');
}

...
<button onClick={foo}>Do stuff</button>

Is that more complicated than plain JS? Creating reusable components:

// MyComponent.jsx:
export default props =>
	<div>
		<h2>{props.header}</h2>
	
		<button onClick={props.onClick}>
			{props.label}
		</button>
	</div>

// Using it:
<MyComponent header="foo" label="bar" onClick={baz} />

Let's take a more useful example. Say you have an image bank app with real-time search filters. Each image has a link URL and a thumbnail. A new array of results gets retrieved from an API whenever a user changes any of the filters.

Ignoring the search function, let's see how you'd render the list of results:

<div className="d-grid gap-2">
	{results.map((index, result) => 
		<a href={result.url} key={index}>
			<img src={result.thumbnail} />
		</a>
	)}
</div>

The only piece of JS you need is a single map() call on an array. Doing the same with plain JS would involve a lot of code with direct DOM manipulation every time the results change. You'd empty the container div, then manually populate it with new elements, setting the attributes of each result element. And rendering performance would be bad compared to using a virtual DOM.

However, this an extremely simple component. Imagine a more complex item with timestamps, tags, comments, nested components, etc. That would be a nightmare with plain JS.

Then we have the fact that the package managers for JS are really bad, and you also need to clean your code, and assemble it to even make it work.

They're not inherently bad. They can be used badly, just like composer. You build and minify JS bundles for production, but I don't see how that's an issue. If Laravel's vendor directory could be trimmed and optimized, everyone would do that in prod.

I know it's not, but I think it should be.

Then it wouldn't solve the problems that React tries to solve.

I'm not even a huge fan of React, but there are a lot of benefits, which is why I tend to use it for non-trivial UIs. I find it a lot faster to develop on. I also like snappy navigation as a user.

But I'm really derailing the thread now, so I'll stop.

JussiMannisto's avatar

@jlrdw

So I mostly use plain javascript and axios now. (...) I would still use jquery over some of these new frameworks that change every 4 to 6 months.

React is 11 years old. It's neither new nor unstable. If it broke down after an update every 6 months, nobody would use it. But it's used everywhere.

It's fine if you don't like something. But why give opinions on something you haven't even learned because you've rejected it on principle? I wouldn't give opinions on NextJS or Livewire because I haven't really used them. All I could do is state my prejudices

Tray2's avatar

@JussiMannisto and this is why I don't like it.

React is not about sprinkling in JS code. If you use it, you write your entire UI with it.

However, we are likely never to agree on this.

Alewa's avatar
Level 2

@JussiMannisto ViewProductAttribute.jsx

Alewa's avatar
Level 2

@JussiMannisto The problem is when I add the ProductAttriute it comes in a string form but the api want it to be added in array object form in my react js, that is the error am having, I am net to react js and I don't know how to add multiple data at once in an array form. I think the error could be either this code

const handleInput = (e) => {
        e.persist();
        setProductAttributeInput({
            ...productAttributeInput,
            [e.target.name]: e.target.value,
        });
    };```

Or this code

async function addProductAttribute(e) { e.preventDefault();

    const Formdata = {
        size: productAttributeInput.size,
        sku: productAttributeInput.sku,
        cost_price: productAttributeInput.cost_price,
        sales_price: productAttributeInput.sales_price,
        stock: productAttributeInput.stock,
    };```

I think I have to convert my input data from string to array, any help?

Please or to participate in this conversation.