How do I reduce the amount of markup in my reactjs/JSX - reactjs

I want to cleanup my JSX to separate the presentation markup from the functional markup/DOM elements.
I have a form which will be the top-level of my component hierarchy. Underneath there will be several inputs and form elements to make up the complete component hierarchy. There will also be a fair amount of twitter bootstrap "cruft" that is mainly there to control presentation.
For example:
render: function() {
return (
<form role="form" className="form-horizontal">
<div className="form-group">
<label htmlFor="homePrice">Home Price</label>
<div className="input-group input-group-lg">
<span className="input-group-addon">$</span>
<input id="homePrice"
className="form-control"
onChange={this.priceChange}
value={this.state.homePrice}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="depositAmount">Deposit Amount</label>
<div className="input-group input-group-lg">
<span className="input-group-addon">$</span>
<input id="depositAmount"
className="form-control"
onChange={this.depositChange}
value={this.state.depositAmount}
/>
</div>
</div>
... snip ...
Ideally I'd have separate components for <form> and then individual child components for each of the <inputs>, without the label tags or <div className="form-group"> and <span className="input-group-addon"> and be able to insert those into various points in the HTML document and maintain component hierarchy.
So how can I accomplish this and maintain the component hierarchy. Changing values in the inputs affects state in the parent, top-most component.
Thanks.

You can do this quite effectively via composition. Just how customizable you want your custom components to be is up to you; with more props and conditional logic, you gain more customizability.
I'll often start by writing the markup/JSX I wish I could use:
render: function() {
return (
<Form horizontal>
<Input id="homePrice"
addon="$" label="Home Price"
onChange={this.priceChange}
value={this.state.homePrice} />
<Input id="depositAmount"
addon="$" label="Deposit Amount"
onChange={this.depositChange}
value={this.state.depositAmount} />
</Form>
);
}
Then you can start implementing the components as necessary to make it work:
var Form = React.createClass({
render: function() {
var direction = "vertical";
if (this.props.horizontal) direction="horizontal";
return (
<form role="form" className={"form-" + direction}
onSubmit={this.props.onSubmit}>
{this.props.children}
</form>
);
}
});
var Input = React.createClass({
render: function() {
return (
<div className="form-group">
<label htmlFor={this.props.id}>{this.props.label}</label>
<div className="input-group input-group-lg">
<span className="input-group-addon">{this.props.addon}</span>
<input id={this.props.id}
className="form-control"
onChange={this.props.onChange}
value={this.props.value} />
</div>
</div>
);
}
});
By utilizing this.props.children, getDefaultProps, the spread operator (e.g. transferring props to a new element via <someElement {...this.props} />), and conditionals, you can create really nice abstractions for more complex components. Additionally, propTypes allows to you specify what properties a component takes, serving as documentation and a way to catch runtime errors in development.
You might consider checking out the source for React Bootstrap to see how they implement composite components to wrap more complex Bootstrap HTML; for example, here's what you'd write to use a tab component:
<TabbedArea defaultActiveKey={2}>
<TabPane eventKey={1} tab="Tab 1">TabPane 1 content</TabPane>
<TabPane eventKey={2} tab="Tab 2">TabPane 2 content</TabPane>
</TabbedArea>
If you're more interested in describing the structure of your forms and then letting a library create the elements automatically, you might look into projects like React Forms:
function Person(props) {
props = props || {}
return (
<Schema name={props.name} label={props.label}>
<Property name="first" label="First name" />
<Property name="last" label="Last name" />
</Schema>
)
}
var family = (
<Schema>
<Person name="mother" label="Mother" />
<Person name="father" label="Father" />
<List name="children" label="Children">
<Person />
</List>
</Schema>
)
React.renderComponent(
<Form schema={family} />,
document.getElementById('example'))

Related

Accessing refs in dynamically created child components react

How would I go about creating refs on child components created by a map function?
So I'm trying to use
"#react-google-maps/api"
to create input fields wrapped by google's autocomplete. However I'm running into an issue where I want to allow the user to create inputs (to add waypoints) and the only way to get their input into an arry is by using refs
<div className={style.form}>
<Autocomplete>
<input type="text" id="from" ref={originRef} placeholder="Enter Starting Location"/>
</Autocomplete>
{wayPoints.map((input, index) => {
return(
<Autocomplete key={index} onChange={e => handleInputChange(index, e)}>
<input type="text" id="from" placeholder="Enter Stop"/>
</Autocomplete>
)
})
}
<Autocomplete>
<input type="text" id="from" ref={destinationRef} placeholder="Enter Ending Location"/>
</Autocomplete>
<div className={style.add} onClick={addNewStop}>
<FaPlus/>
</div>
</div>
However since I'm creating child compoents I'm not sure how to use refs to solve the problem. I tried using a onChange handler function but if you click on the autocomplete recommendation it doesnt save.

URL search parameters gets replaced - Remix Run

I'm working on a search UI where I have quite a few filters which I want as URL parameters when someone selects/checks the options. I've used the technique as advised on the Remix.run docs to come up with multiple forms within the filters. Each time a group of Filters gets submitted, the selected old parameters get disappeared. Heres my code,
<Panel header="Status" key="status">
<Form
name="search"
action='/search'
method="get"
onChange={(e) => submit(e.currentTarget, { replace: false })}
>
<ul>
<li>
<Checkbox
name="status"
value="buy_now"
defaultChecked={status.includes('buy_now')}
>
Buy Now
</Checkbox>
</li>
<li>
<Checkbox
name="status"
value="on_auction"
defaultChecked={status.includes('on_auction')}
>
On Auction
</Checkbox>
</li>
</ul>
</Form>
</Panel>
<Panel header="Price" key="price">
<Form name="search" action='/search' method="get">
<Select
name="blockchain"
value={
blockchain
? options.filter((a) => a.value === blockchain)
: undefined
}
options={options}
placeholder="Blockchain"
type="white"
/>
<div className="d-flex align-center price">
<TextInput
value={min ? min : undefined}
name="min"
placeholder="Min"
/>
<span>to</span>
<TextInput
value={max ? max : undefined}
name="max"
placeholder="Max"
/>
</div>
<button
onClick={(e) => {
e.stopPropagation()
submit(e.currentTarget, { replace: false })
}}
className="btn primary-btn btn-lg w-100"
>
Apply
</button>
</Form>
</Panel>
How Can I get around this to have all the parameters without having to manage them on my own using React state?
Edit:- I want the first filter to be submitted automatically and the latter to be submitted on a button click.
Bit of a UI of what I'm trying to achieve,
Answer: After investing enough time to look through for shortcuts, finally understood that it's not one of the magic that remix.run does. use something like formik and update the state imparatively.
When you submit a form, the only values included are the one under the submitted form. The values from any other form are not included (fortunately!).
So I'd use a single Form with all the inputs under it (checkboxes as well as text inputs).
Then instead of a onChange on the Form, you can add something like an onChange handler on the checkboxes and submit the form inside imperatively (using a ref click on the submit button or something, I think using a ref on the form you need to submit all values in the submit function so a button ref click may be simpler).
Keep in mind that if you want to "restore" the field values after submitting, you need to return them from the loader function like this:
// Loader function
const url = new URL(request.url);
return {
results: [...],
values: Object.fromEntries(url.searchParams.entries())
};
Then in the component, use values from useLoaderData:
<input type="text" name="max" defaultValue={values.max || ""}/>
Added benefit: if you come back to this page (by clicking browser back for example), your search parameters and search results are still there!
I actually put up a stackblitz for you but I lost all my changes :(
It seems like you could just keep all fields in a single form and submit that form when the submit button is pressed.
Then onChange, check if the target's name is 'status', and submit the form anyway.
export default function App() {
const submit = (form) => {
form.submit();
};
return (
<form
name="search"
action="/search"
method="get"
onChange={(e) => {
if (e.target.name === "status") {
submit(e.currentTarget);
}
}}
>
<fieldset>
<legend>status</legend>
<label>
<input type="checkbox" name="status" value="buy_now" />
buy_now
</label>
<label>
<input type="checkbox" name="status" value="on_auction" />
on_auction
</label>
</fieldset>
<fieldset>
<legend>price</legend>
<label>
<div>blockchain</div>
<select name="blockchain">
<option value="option_1">Blockchain Option 1</option>
<option value="option_2">Blockchain Option 2</option>
</select>
</label>
<label>
min <input type="number" name="min" />
</label>
<label>
max <input type="number" name="max" />
</label>
</fieldset>
<button type="submit">Apply</button>
</form>
);
}
demo
Note: not sure what your motivation is to want to separate this into separate forms, but I think the magic you're referring to is that server state, URLSearchParams, FormData and UI are all aligned because they are using the same underlying data using only common web APIs.

React 'fetch' response successful, but setState not working

I'm new to React, working through a ".Net core CRUD with React" tutorial and trying to tweak it along the way to suit my own needs.
The page I'm dealing with here is an Add/Edit entry page. It works fine for rendering a default form with default values but doesn't render anything if the values are collected from a fetch call.
The important details are below:
interface AddPortfolioProjectDataState {
title: string;
projectData: PortfolioProject;
loading: boolean;
}
The page is told to render as follows:
public render() {
let contents = this.state.loading
? <p><em>Loading Project...</em></p>
: this.renderCreateForm(this.state.projectData.type, this.state.projectData.tech);
return (
<div>
<h1>{this.state.title}</h1>
<h3>Project</h3>
<hr />
{contents}
</div>
)
}
If I want to add a new item, therefore using a default PortfolioProject object with default values, it works fine. However, if I want to edit an old entry, I have to grab it from the server, like so:
fetch('api/StuartAitkenWebsite/GetPortfolioProject/' + projID)
.then(response => response.json() as Promise<PortfolioProject>)
.then(data => {
this.setState({ title: "Edit", loading: false, projectData: data });
});
In the debug console on Firefox, I can see the whole server process runs smoothly:
GET http://localhost:62669/api/StuartAitkenWebsite/GetPortfolioProject/2
Response payload: {"id":2,"name":"Particles Sim","projectDate":"2017-01-01T00:00:00","projectDurationWeeks":1,"type":"Desktop App","tech":"C++, SFML","views":0,"creationDate":"2018-10-22T00:00:00","modifiedDate":"2018-10-22T00:00:00","status":1}`
It gives a JSON output of the payload too, which I can't easily copy-paste here so I'll give a screenshot:
There are no server error responses, no React errors, nothing.
But that's as far as it gets.
The page remains showing 'loading', even though the data is there and ready and wants to be displayed.
From this, I can gather that the final step of the fetch call is not succeeding, because this.setState({ title: "Edit", loading: false, projectData: data }); is clearly not having any effect on the page data.
I have other fetch calls which look exactly the same but work fine. I can't see what I'm missing here.
The one and the only difference I notice is this:
When I use this component to create a fresh 'Add Project' form, the state is set like so:
this.state = {
title: "Create",
loading: false,
projectData: new PortfolioProject,
};
But when I do it from the API, it's set like so:
this.setState({
title: "Edit",
loading: false,
projectData: data
});
The successful version uses this.state, and the unsuccessful version uses this.setState
I don't know what this can mean though. As I said, no errors are being thrown, I'm sticking to the tutorial format, and it works fine in other parts of the project.
Thanks.
UPDATE
I've put a log in at the point where renderCreateForm() is called. It seems setState is actually working. Therefore, the problem must be in renderCreateForm() so I'll post that code below. Sorry it's sort of large.
private renderCreateForm(projectTypes: string, projectTech: string) {
console.log(this.state.loading); // "false"
console.log(this.state.projectData); //"Object { id:1, name: "Muon Detector".. etc
//so the render is getting the data
return (
<form onSubmit={this.handleSave}>
<div className="form-group row" >
<input type="hidden" name="Id" value={this.state.projectData.id} />
</div>
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="Name">Name</label>
<div className="col-md-4">
<input className="form-control" type="text" name="Name" defaultValue={this.state.projectData.name} required />
</div>
</div>
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="ProjectDate">Project Date</label>
<div className="col-md-4">
<input className="form-control" type="date" name="ProjectDate" defaultValue={this.state.projectData.creationDate.toDateString()} required />
</div>
</div >
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="ProjectDurationWeeks">Project Duration (weeks)</label>
<div className="col-md-4">
<input className="form-control" type="text" name="ProjectDurationWeeks" defaultValue={this.state.projectData.projectDurationWeeks.toString()} required />
</div>
</div >
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="Type">Project Type</label>
<div className="col-md-4">
<input className="form-control" type="text" name="Type" defaultValue={this.state.projectData.type} required />
</div>
</div >
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="Tech">Project Tech</label>
<div className="col-md-4">
<input className="form-control" type="text" name="Tech" defaultValue={this.state.projectData.tech} required />
</div>
</div >
<div className="form-group row" >
<input type="hidden" name="Views" value={this.state.projectData.views} />
</div>
<div className="form-group row" >
<input type="hidden" name="CreationDate" value={this.state.projectData.creationDate.toDateString()} />
</div>
<div className="form-group row" >
<input type="hidden" name="ModifiedDate" value={this.state.projectData.modifiedDate.toDateString()} />
</div>
<div className="form-group row" >
<input type="hidden" name="Status" value={this.state.projectData.status} />
</div>
<div className="form-group">
<button type="submit" className="btn btn-default">Save</button>
<button className="btn" onClick={this.handleCancel}>Cancel</button>
</div >
</form>
)
}
UPDATE 2: Added some screenshots showing how things appear so far.
How the main data table page looks:
If I click 'Add New', it works:
(the 'Save' option works there too. Data posts to the server and will list on the main portfolio page)
Clicking Edit for any of the entries does not work, it gets this far:
The 'Loading Project...' text comes from the render() call for this page, as is shown in the code posted at the top of this post.
The page is supposed to look exactly like the 'Create' page (2nd screenshot), but with the title being 'Edit', and with input values populated from the given data.
The solution was absurd, but may certainly help others...
The renderCreateForm() method (as shown in Update 1 of the post) was not working because of the .toDateString() method I was using in a few of the inputs.
I changed it to .toString() and now everything works.
For example, with an input like this:
<input className="form-control" type="date" name="ProjectDate" defaultValue={projectData.creationDate.toDateString()} required />
I changed it to this:
<input className="form-control" type="date" name="ProjectDate" defaultValue={projectData.creationDate.toString()} required />
Note the defaultValue property of the input.
Repeat for all cases of .ToDateString(), and it now works,
Amazing that this didn't bring up an error anywhere. I thought Typescript and all these various frameworks were supposed to get around the issue of Javascript silently failing like that. This has been my longest and most time-wasting 'silent fail error' ever, by a very long margin.

Forms with React components

I want to create a form with React. I came up with the following:
export class Welcome extends Component {
constructor(props) {
super(props);
this.state = {
errors: []
};
}
render() {
return (
<form className="Welcome">
<div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>
<div className="question-box">
<div className="question"><span className="underline" >How much time do you have?</span></div>
<input className="minutes" type="text" value={this.props.minutes}
onChange={ (e) => this.props.updatePreferences("minutes", e.target.value) }/> minutes.
</div>
<div className="question-box">
<div className="question"><span className="underline">What do you fancy?</span></div>
<div className="answer">
<span className="choice">
<input type="checkbox" id="business" defaultChecked={ this.props.interests.business }/>
<label htmlFor="business">Business</label>
</span>
<span className="choice">
<input type="checkbox" id="code" defaultChecked={ this.props.interests.code }/>
<label htmlFor="code">Code</label>
</span>
<span className="choice">
<input type="checkbox" id="design" defaultChecked={ this.props.interests.design } />
<label htmlFor="design">Design</label>
</span>
</div>{/* end of .answer*/}
</div>{/* end .question-box*/}
<button>Show me magic</button>
<div className="errors">
No error. All good.
</div>
</form>
);
}
}
The onChange functions are in the parent component which also holds the state. But every time they are called the whole component is reloaded. Should the whole form be on a separate component or I should create separate components for each input?
React call render function in response of state change. So if component does not receive state change event it most probably will not rerendered but not necessarily. It may rernder anyway. ref

Label doesn't float when dynamically setting Textfield value in Material Design Light and React

When I dynamically set the value (i.e. update the prop not via typing) then the label does not move out of the way.
My code is
render: function() {
// Removed some minor logic here that isn't related
return(
<div className={classes}>
<div className={_mdlInputClassNames} ref="inputContainer">
<input
ref="input"
type="text"
id={this.props.id}
className="mdl-textfield__input"
data-upgraded
name={this.props.name}
value={this.props.value}
onKeyDown={this.props.onKeyDown}
onKeyUp={this.props.onKeyUp}
onChange={this._onChange}
onBlur={this.props.onBlur}
autoComplete="off" />
<label
htmlFor={this.props.id}
className="mdl-textfield__label" >
{this.props.label}
</label>
<div className={msgClasses}>{msg}</div>
</div>
</div>
);
},
componentDidUpdate: function() {
// THIS DOESNT DO ANYTHING
// var inputContainer = this.refs.inputContainer.getDOMNode();
// componentHandler.upgradeElement(inputContainer, 'MaterialTextfield');
},
From what I can find online, upgrading the element should work. But it doesn't do anything.
Looking at the DOM Element, it already has a is-upgraded class on it, but not the is-dirty class which is the one that seems to actually move the label.
Any help would be great
This works for me:
$("#inputId").val("thevalue").parent().addClass("is-dirty");

Resources