How to pass props stated in HTML to root component - javascript

I'm using a simple component in React for two buttons in an existing HTML/JavaScript, (not a React project) project. It looks like this:
//Submitcancel.jsx
'use strict'
class Submitcancel extends React.Component {
constructor(props) {
super(props)
console.log(props)
}
render() {
return (
<div className="form-buttons">
<div className="ibm-col-12-12">
<button id="buttonSubmit" name="buttonSubmit" value="Submit" type="submit" className="ibm-btn-pri dw-btn-blue">Submit</button>
<button value="Cancel" id="buttonCancel" name="buttonCancel" className="ibm-btn-sec dw-btn-blue">Cancel</button>
</div>
</div>
)
}
}
ReactDOM.render(
// React.createElement(Submitcancel),
// document.querySelector('#react-submit-cancel')
)
The HTML file looks like this:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<!-- Load React component. -->
<script type="text/babel" src="./js/components/Submitcancel.jsx"></script>
The component element where I would like to define the props is like this:
<div id="react-submit-cancel"></div>

If you want to grab the button texts from your HTML <div>, you need a non-react solution for that:
<div id="react-submit-cancel" submitText="Go"></div>
then in your initialization:
const el = document.querySelector('#react-submit-cancel');
const props = {
submitText: el.getAttribute("submitText") || "Submit", // default value
cancelText: el.getAttribute("cancelText") || "Cancel"
};
ReactDOM.render(React.createElement(Submitcancel, props), el)
For a pure React solution you'd have to wrap the Submitcancel component so you can pass props to it using JSX.

When you need to pass data through props, you just need to mention props id and value along with component.
In your case code will be like:
ReactDOM.render(
<Submitcancel FirstName={"first name"} LastName={"last name"}/>,
document.getElementById("react-submit-cancel")
)
Above example FirstName and LastName are two props
You can get the value in constructor inside the Submitcancel component.
constructor(props) {
super(props)
console.log(props.FirstName)
console.log(props.LastName)
}

Please follow this code:
ReactDOM.render(
<Submitcancel />,
document.getElementById("react-submit-cancel")
)

Related

Svelte keep default prop value of a child component

I have component1 that takes let text as a prop and then component2 that does almost the same thing, but I'd like to keep component1 separate for better reusability.
So I wrapped the comp1 (Child.svelte) with comp2 (Wrapper.svelte). But how do I keep the default prop value of the Child component without writing it again?
here is an example:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text = 'hello world'; //need to type the default value again
</script>
<Child text={text} />
//Child.svelte
<script lang="ts">
export let text = 'hello world';
</script>
<p>{text}</p>
Thank you #hackape and #Stephane Vanraes for your answers!
the answer from #hackape seems like the answer I was looking for, but It still throws this typescript error: Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322) when I don't provide any value to Wrapper comp. from the outside.
I should have realised this earlier, but I combined both answers and came up with this:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string = undefined;
</script>
<Child bind:text />
also works with <Child text={text}/>
I am relatively new to Stack Overflow, should I accept my or #hackapes answer?
Use bind:prop to create a two way binding. Docs: https://svelte.dev/tutorial/component-bindings
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string
</script>
<Child bind:text />

Sample ReactJS from reactjs.org code not working with JSX

I am trying to follow the code sample given in this link: https://reactjs.org/docs/add-react-to-a-website.html#add-react-in-one-minute to run a react component into an existing HTML page.
but when I am trying to replace the native JavaScript with JSX I am getting this error:
ReferenceError: e is not defined
I know I need to replace the e(LikeButton)) with something. but it's not mentioned there what to update in render code.
likebutton.js:
'use strict';
// const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
// Display a "Like" <button>
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);
}
}
index.html:
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<!-- Load our React component. -->
<script src="{{ asset('theme_assets/js/react/likebutton.js') }}" type="text/babel"></script>
<script>
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
</script>
Replace
ReactDOM.render(e(LikeButton), domContainer);
With
ReactDOM.render(<LikeButton />, domContainer);
Working Code here
https://jsbin.com/wuqoluyovu/edit?html,console,output

How to create and render a React Component after babelify/transpiling?

I have a hello world react component that is written in JSX, transpiled with babel, and then included in the hello.html template of a Flask app. What I have working is creating and rendering the component before transpiling as such:
const hello = <Hello name="world" />;
ReactDOM.render(hello, document.getElementById('hello'));
How can I do those two steps in a <script> tag in my hello.html template? My goal is to be able to pass that name variable from the template to the component and then render it.
A little more context:
The JSX hello.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom'
import { render } from 'react-dom'
class Hello extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>Hello {this.props.name}!!!</div>
)
}
}
//The following works:
//const hello = <Hello name="world" />;
//ReactDOM.render(hello, document.getElementById('hello'));
hello.html looks like this:
<html>
<head>
</head>
<body>
<div>ASDF</div>
<div id="hello"></div>
</body>
{# The following line is a post babelify (transpiled) hello.js #}
<script type="text/javascript" src="{{ url_for('static', filename='js/hello.js') }}"></script>
<script type="text/javascript">
{#
What goes here? The code in the above section does not work.
The transpiled code defines a "var Hello = /*#__PURE__*/ function (_React$Component) { ...".
const hello = Hello(); does not throw an error, but also does not render or pass an argument.
hello.render(); is also something that I have tried, along with arguments for div/id to render in and name.
#}
</script>
</html>
Correction: Calling Hello() does not throw an error if the script is text/babel, in which case the script probably isn't doing anything.
The Flask route looks like this:
#app.route(u'/')
def index():
return render_template(u'hello.html', name="universe")
Two ways you can pass variables from your server application to react component:
Use the html data-variable prop.
Create a global variable. Something like window.variable
Then you should be able to access variable as a props like props.variable in your react-component.
My recommended approach I would take is to use a bundler such as SystemJS (version 2), and you will have something like the following:
<!DOCTYPE html>
<html>
<head>
<script src="node_modules/core-js-bundle/minified.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script type="systemjs-importmap" src="systemjs.imports.json"></script>
<script src="node_modules/systemjs/dist/system.min.js"></script>
<script src="node_modules/systemjs/dist/extras/named-exports.min.js"></script>
<script>
System.import('../.playground/index.js').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<div>ASDF</div>
<div id="hello"></div>
</body>
</html>
And index.js will look something like this
ReactDOM.render(
(< Hello/>),
document.getElementById('app')
);
Then your systemjs-importmap will look like this
{
"imports": {
"react": "../node_modules/react/umd/react.production.min.js",
"react-dom": "../node_modules/react-dom/umd/react-dom.production.min.js",
// ... other named exports you want to add like the Hello component here
}
}

vue.js passing prop through script

So I’m passing a component as a variable through the store e.g.
<template>
<div>
<component :is="store.state.General.body"></component>
</div>
</template>
<script>
import store from "#/store"
</script>
Now I was wondering how I would pass the component with props because this is how I’m doing it:
<script>
import Input from "#/components/Input"
methods: {
example() {
store.commit("general_set_modal", {body: Input, title: "New "+page})
}
</script>
it’s being rendered properly, but just lacks the desired props.
I'd do something like
<template>
<div>
<component :is="store.state.General.body" v-bind="store.state.General.props"></component>
</div>
</template>
<script>
import store from "#/store"
</script>
and have the store item look like
<script>
import Input from "#/components/Input"
methods: {
example() {
store.commit("general_set_modal", {body: Input, props: {title: "New "+page}})
}
</script>

How to run script in react

Hey I have a react application and I have a input field that I would like to mask (type="password") while typing the actual password.
I have found a javascript code that does what I need but I cannot seem to make it run with React.
here is the code of the masking function:
http://pastebin.com/vqqaiDuB
but I just cant use it in my view component.
I did try to :
module.exports = MaskedPassword;
but was not able to use the class?!
I am surely missing something big...
how I import it:
import maskedInput from './../../public/MaskedPassword';
this is how my component looks like:
export default class DriversLicense extends Component {
constructor(props){
super(props);
this.state ={};
}
componentDidMount() {
maskedInput(document.getElementById("demo-field"), '\u25CF');
}
render() {
return (
<div>
<form id="demo-form" action="#">
<fieldset>
<input type="password" className="password" id="demo-field" name="pword" onChange={this.demoChange}/>
</fieldset>
</form>
</div>
);
}
}
which gives me:
this.createContextWrapper is not a function
Normally this is the way to call external libraries to make changes to components after render, I would suggest to find the react version of your library because maybe It will have problems with the binding (this). Hope this example helps.
function maskedInput(ele, symbol, obj) {
//this here is not the function
ele.value = this.someOtherFunction()
}
maskedInput.prototype = {
someOtherFunction: function(){
return "Hello"
}
}
function maskedInputGood(ele, symbol, obj) {
const someOtherFunction = function(){
return "Hello"
}
ele.value = someOtherFunction()
}
maskedInput.prototype = {
someOtherFunction: function(){
return "Hello"
}
}
var App = React.createClass({
componentDidMount() {
maskedInputGood(document.getElementById("demo-field"), '\u25CF');
maskedInput(document.getElementById("demo-field"), '\u25CF');
},
render() {
return (
<div>
<form id="demo-form" action="#">
<fieldset>
<input type="password" className="password" id="demo-field" name="pword" onChange={this.demoChange}/>
</fieldset>
</form>
</div>
);
}
})
ReactDOM.render(<App />,document.getElementById('app'))
<html>
<body>
<div id='app'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>
</html>
It seems to me the library is not properly encapsulated, or some similar problem. Have you tried using a React component like this one: https://www.npmjs.com/package/react-password-mask
Since its a React component, it will be more natural to integrate it in your code.
Does your maskedPassword library have any feature that react-password-mask is missing?

Categories