jsx react code example
Example 1: html to jsx
1) Option One: Online
https://magic.reactjs.net/htmltojsx.htm
or
https://transform.tools/html-to-jsx
2) Option Two: System (assuming you have npm)
npm install html-to-jsx
Example 2: jsx full form
Thr process of using HTML in react is known as JSX
Example 3: javascript react
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<label htmlFor="new-todo">
What needs to be done?
</label>
<input
id="new-todo"
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (this.state.text.length === 0) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(state => ({
items: state.items.concat(newItem),
text: ''
}));
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('todos-example')
);
Example 4: jsx react
const element = <h1>Hello World</h1>
Example 5: react ctx
ctx is a NextJS artifact.
ctx is a context object containing those properties (Source):
pathname - path section of URL
query - query string section of URL parsed as an object
asPath - String of the actual path (including the query) shows in the browser
req - HTTP request object (server only)
res - HTTP response object (server only)
err - Error object if any error is encountered during the rendering
Example 6: create react element with string
mport React from 'react'
const MyComponent = 'div'
function App() {
return (
<div>
<h1>Hello</h1>
<hr />
<MyComponent>
<h3>I am inside a {'<div />'} element</h3>
</MyComponent>
</div>
)
}